Spaces:
Sleeping
feat: découpage en zones (remplace le regroupement par sous-famille)
Browse filesL'onglet 2 devient « ✂️ Découper en zones » : on lit le CSV SANS ignorer aucune
ligne, et à chaque rupture — séparation (ligne vide) ou décalage de données
(titre de section dont la structure de colonnes change) — on coupe et tout ce
qui suit part dans un nouveau CSV.
- core/zone_split.py : split_into_zones() + write_zones(). Détection séparateur
= ligne vide | 1 seule cellule remplie | nombre de colonnes ≠ en-tête.
- Sortie numérotée zone_01.csv, zone_02.csv… (l'utilisateur nomme à la main) ;
colonnes/valeurs d'origine préservées ; rapport listant le séparateur de
chaque zone.
- app_gradio : onglet zones (récap + ZIP), suppression du mapping/sous-familles
côté UI.
- tests : +9 (core.zone_split), suite à 73 verts.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- app.py +1 -1
- app_gradio.py +65 -268
- core/zone_split.py +137 -0
- tests/test_zone_split.py +76 -0
|
@@ -3,7 +3,7 @@ Point d'entrée du Space : FastAPI minimal + UI Gradio à onglets servie sur /.
|
|
| 3 |
|
| 4 |
Une seule page, deux onglets :
|
| 5 |
- 🧹 Nettoyeur CSV (core.cleaner — 100 % local, sans IA)
|
| 6 |
-
-
|
| 7 |
|
| 8 |
Lancement (Docker) : uvicorn app:app --host 0.0.0.0 --port 7860
|
| 9 |
"""
|
|
|
|
| 3 |
|
| 4 |
Une seule page, deux onglets :
|
| 5 |
- 🧹 Nettoyeur CSV (core.cleaner — 100 % local, sans IA)
|
| 6 |
+
- ✂️ Découper en zones (core.zone_split — coupe à chaque séparation / décalage)
|
| 7 |
|
| 8 |
Lancement (Docker) : uvicorn app:app --host 0.0.0.0 --port 7860
|
| 9 |
"""
|
|
@@ -18,30 +18,11 @@ import gradio as gr
|
|
| 18 |
from dotenv import load_dotenv
|
| 19 |
|
| 20 |
from core.cleaner import clean_csv
|
| 21 |
-
from core.
|
| 22 |
-
read_csv_df, guess_col, csv_to_articles, GUESS, NONE_COL,
|
| 23 |
-
)
|
| 24 |
-
from core.csv_writer import (
|
| 25 |
-
export_articles_par_famille, COLS_ARTICLES_EBP, _build_article_ebp_row,
|
| 26 |
-
)
|
| 27 |
-
from core.subfamily import analyse_sous_familles
|
| 28 |
|
| 29 |
load_dotenv()
|
| 30 |
|
| 31 |
|
| 32 |
-
# ── Constantes ────────────────────────────────────────────────────────────────
|
| 33 |
-
|
| 34 |
-
TVA_CHOICES = [("20 %", 20.0), ("10 %", 10.0), ("5,5 %", 5.5)]
|
| 35 |
-
PREVIEW_N = 10 # nombre de références montrées dans l'aperçu éditable
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def _resolve_tva(label: str) -> float:
|
| 39 |
-
for lab, val in TVA_CHOICES:
|
| 40 |
-
if lab == label:
|
| 41 |
-
return val
|
| 42 |
-
return 20.0
|
| 43 |
-
|
| 44 |
-
|
| 45 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 46 |
# ONGLET 1 — Nettoyeur CSV
|
| 47 |
# ══════════════════════════════════════════════════════════════════════════════
|
|
@@ -94,211 +75,63 @@ def run_clean(csv_file, drop_empty, drop_duplicates, trim_whitespace,
|
|
| 94 |
|
| 95 |
|
| 96 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 97 |
-
# ONGLET 2 —
|
| 98 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 99 |
|
| 100 |
-
def
|
| 101 |
-
"""
|
| 102 |
-
|
| 103 |
-
empty_opt = gr.update(choices=[NONE_COL], value=NONE_COL)
|
| 104 |
-
if csv_file is None:
|
| 105 |
-
return empty, empty, empty_opt, empty_opt, ""
|
| 106 |
-
try:
|
| 107 |
-
df = read_csv_df(csv_file.name)
|
| 108 |
-
except Exception as exc:
|
| 109 |
-
return empty, empty, empty_opt, empty_opt, f"❌ Lecture impossible : {exc}"
|
| 110 |
-
|
| 111 |
-
cols = [str(c) for c in df.columns]
|
| 112 |
-
ref = guess_col(cols, GUESS["reference"])
|
| 113 |
-
lib = guess_col(cols, GUESS["libelle"])
|
| 114 |
-
prix = guess_col(cols, GUESS["prix"])
|
| 115 |
-
unite = guess_col(cols, GUESS["unite"])
|
| 116 |
-
|
| 117 |
-
req = lambda v: gr.update(choices=cols, value=v or (cols[0] if cols else None))
|
| 118 |
-
opt = lambda v: gr.update(choices=[NONE_COL] + cols, value=v or NONE_COL)
|
| 119 |
-
info = f"{len(df)} ligne(s), {len(cols)} colonne(s) : {', '.join(cols[:8])}{'…' if len(cols) > 8 else ''}"
|
| 120 |
-
return req(ref), req(lib), opt(prix), opt(unite), info
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
# ── Aperçu éditable ───────────────────────────────────────────────────────────
|
| 124 |
-
|
| 125 |
-
def _articles_to_preview(articles, params, n) -> list[list[str]]:
|
| 126 |
-
rows = []
|
| 127 |
-
for a in articles[:n]:
|
| 128 |
-
r = _build_article_ebp_row(
|
| 129 |
-
a, params["fournisseur_code"], params["remise"],
|
| 130 |
-
"TVA20", params["taux_tva"], params["prix_sont_ttc"],
|
| 131 |
-
)
|
| 132 |
-
rows.append([r[c] for c in COLS_ARTICLES_EBP])
|
| 133 |
-
return rows
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
def _apply_preview_edits(articles, edited_rows):
|
| 137 |
-
"""
|
| 138 |
-
Réinjecte les corrections de l'aperçu (libellé, prix HT, unité, famille)
|
| 139 |
-
par appariement sur le « Code article ». Code article reste verrouillé.
|
| 140 |
-
"""
|
| 141 |
-
if edited_rows is None:
|
| 142 |
-
return articles
|
| 143 |
-
rows = edited_rows.values.tolist() if hasattr(edited_rows, "values") else list(edited_rows)
|
| 144 |
-
idx = {c: i for i, c in enumerate(COLS_ARTICLES_EBP)}
|
| 145 |
-
by_ref: dict[str, dict] = {}
|
| 146 |
-
for a in articles:
|
| 147 |
-
ref = str(a.get("reference") or "").strip()
|
| 148 |
-
if ref and ref not in by_ref:
|
| 149 |
-
by_ref[ref] = a
|
| 150 |
-
for row in rows:
|
| 151 |
-
if not row or len(row) < len(COLS_ARTICLES_EBP):
|
| 152 |
-
continue
|
| 153 |
-
ref = str(row[idx["Code article"]]).strip()
|
| 154 |
-
a = by_ref.get(ref)
|
| 155 |
-
if a is None:
|
| 156 |
-
continue
|
| 157 |
-
a["nom_dessin"] = str(row[idx["Libellé"]]).strip()
|
| 158 |
-
a["unite"] = str(row[idx["Code unité"]]).strip()
|
| 159 |
-
a["code_sous_famille"] = str(row[idx["Code sous-famille article"]]).strip().upper()
|
| 160 |
-
pvht = str(row[idx["PV HT public conseillé"]]).replace(",", ".").strip()
|
| 161 |
-
try:
|
| 162 |
-
if pvht:
|
| 163 |
-
a["prix_conseille"] = float(pvht)
|
| 164 |
-
except ValueError:
|
| 165 |
-
pass
|
| 166 |
-
return articles
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
# ── Export ────────────────────────────────────────────────────────────────────
|
| 170 |
-
|
| 171 |
-
def _build_rapport(valides, rapport_familles, params) -> str:
|
| 172 |
lines = [
|
| 173 |
-
"═══
|
| 174 |
-
f"
|
| 175 |
-
f"
|
| 176 |
-
f"
|
|
|
|
|
|
|
| 177 |
]
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
"── Analyse des sous-familles ──",
|
| 182 |
-
f"Total classé : {rapport_familles['total']}",
|
| 183 |
-
f" par règles : {rapport_familles['par_regles']}",
|
| 184 |
-
f" par LLM : {rapport_familles['par_llm']}",
|
| 185 |
-
f" par défaut : {rapport_familles['par_defaut']}",
|
| 186 |
-
"Répartition (1 CSV par famille) :",
|
| 187 |
-
]
|
| 188 |
-
for fam, n in rapport_familles["repartition"].items():
|
| 189 |
-
lines.append(f" • articles_{fam}.csv : {n} article(s)")
|
| 190 |
return "\n".join(lines)
|
| 191 |
|
| 192 |
|
| 193 |
-
def
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
fournisseur_code=params["fournisseur_code"],
|
| 200 |
-
remise=params["remise"],
|
| 201 |
-
taux_tva=params["taux_tva"],
|
| 202 |
-
prix_sont_ttc=params["prix_sont_ttc"],
|
| 203 |
-
)
|
| 204 |
-
|
| 205 |
-
# Fichier familles articles (codes distincts) — format écran EBP « Familles Articles »
|
| 206 |
-
familles = sorted({a.get("code_sous_famille", "DIVERS") for a in valides})
|
| 207 |
-
fam_path = os.path.join(out_dir, "0_familles_articles.csv")
|
| 208 |
-
with open(fam_path, "w", newline="", encoding="utf-8-sig") as f:
|
| 209 |
-
f.write("Code Famille Articles;Famille Articles\r\n")
|
| 210 |
-
for fam in familles:
|
| 211 |
-
f.write(f"{fam};{fam}\r\n")
|
| 212 |
-
|
| 213 |
-
rapport_txt = _build_rapport(valides, rapport_familles, params)
|
| 214 |
-
rapport_path = os.path.join(out_dir, "rapport.txt")
|
| 215 |
-
Path(rapport_path).write_text(rapport_txt, encoding="utf-8")
|
| 216 |
-
|
| 217 |
-
zip_path = os.path.join(out_dir, "export_ebp.zip")
|
| 218 |
-
with zipfile.ZipFile(zip_path, "w") as zf:
|
| 219 |
-
for fp in Path(out_dir).glob("*.csv"):
|
| 220 |
-
zf.write(fp, fp.name)
|
| 221 |
-
zf.write(rapport_path, "rapport.txt")
|
| 222 |
-
return zip_path, rapport_txt
|
| 223 |
-
|
| 224 |
|
| 225 |
-
# ── Callbacks principaux ──────────────────────────────────────────────────────
|
| 226 |
|
| 227 |
-
def
|
| 228 |
-
fournisseur_code, remise, taux_tva_label, prix_sont_ttc,
|
| 229 |
-
analyse_familles, classif_llm, progress=gr.Progress()):
|
| 230 |
if csv_file is None:
|
| 231 |
-
return None, gr.update(visible=False), "⚠️ Aucun fichier CSV fourni."
|
| 232 |
-
if not ref_col or not lib_col:
|
| 233 |
-
return None, gr.update(visible=False), "⚠️ Choisis au moins les colonnes Référence et Libellé."
|
| 234 |
-
|
| 235 |
-
fournisseur_code = (fournisseur_code or "").strip().upper() or "FOUR001"
|
| 236 |
-
params = {
|
| 237 |
-
"fournisseur_code": fournisseur_code,
|
| 238 |
-
"remise": float(remise),
|
| 239 |
-
"taux_tva": _resolve_tva(taux_tva_label),
|
| 240 |
-
"prix_sont_ttc": bool(prix_sont_ttc),
|
| 241 |
-
"analyse_familles": bool(analyse_familles),
|
| 242 |
-
}
|
| 243 |
-
|
| 244 |
try:
|
| 245 |
progress(0.2, desc="Lecture du CSV…")
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
return None, gr.update(visible=False), "⚠️ Aucune ligne exploitable dans ce CSV."
|
| 250 |
-
|
| 251 |
-
rapport_familles = None
|
| 252 |
-
if analyse_familles:
|
| 253 |
-
progress(0.5, desc="Analyse des sous-familles…")
|
| 254 |
-
client = None
|
| 255 |
-
if classif_llm:
|
| 256 |
-
import anthropic
|
| 257 |
-
try:
|
| 258 |
-
client = anthropic.Anthropic()
|
| 259 |
-
except Exception:
|
| 260 |
-
client = None
|
| 261 |
-
articles, rapport_familles = analyse_sous_familles(
|
| 262 |
-
articles, use_llm=classif_llm and client is not None, client=client,
|
| 263 |
-
)
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
"Corrige le tableau (famille, libellé, prix HT, unité) puis « Exporter ». "
|
| 269 |
-
"L'unité de chaque ligne est laissée telle quelle.")
|
| 270 |
-
progress(1.0, desc="Aperçu prêt")
|
| 271 |
-
return state, gr.update(value=preview_rows, visible=True), info
|
| 272 |
-
except Exception as exc:
|
| 273 |
-
tb = traceback.format_exc()
|
| 274 |
-
return None, gr.update(visible=False), f"❌ Erreur : {exc}\n\n{tb[-600:]}"
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
-
def run_csv_export(state, edited_rows, progress=gr.Progress()):
|
| 278 |
-
if not state:
|
| 279 |
-
return None, "⚠️ Lance d'abord « Analyser & aperçu »."
|
| 280 |
-
try:
|
| 281 |
-
progress(0.3, desc="Application des corrections…")
|
| 282 |
-
valides = _apply_preview_edits(state["valides"], edited_rows)
|
| 283 |
-
params = state["params"]
|
| 284 |
-
|
| 285 |
-
rapport_familles = state.get("rapport_familles")
|
| 286 |
-
if params["analyse_familles"]:
|
| 287 |
-
repart: dict[str, int] = {}
|
| 288 |
-
for a in valides:
|
| 289 |
-
fam = a.get("code_sous_famille", "DIVERS")
|
| 290 |
-
repart[fam] = repart.get(fam, 0) + 1
|
| 291 |
-
if rapport_familles:
|
| 292 |
-
rapport_familles = dict(rapport_familles)
|
| 293 |
-
rapport_familles["repartition"] = dict(sorted(repart.items(), key=lambda kv: -kv[1]))
|
| 294 |
-
|
| 295 |
-
progress(0.6, desc="Écriture des CSV par famille…")
|
| 296 |
-
zip_path, rapport_txt = _do_csv_export(valides, rapport_familles, params)
|
| 297 |
progress(1.0, desc="Terminé !")
|
| 298 |
-
|
|
|
|
| 299 |
except Exception as exc:
|
| 300 |
tb = traceback.format_exc()
|
| 301 |
-
return None, f"❌ Erreur : {exc}\n\n{tb[-600:]}"
|
| 302 |
|
| 303 |
|
| 304 |
# ══════════════════════════════════════════════════════════════════════════════
|
|
@@ -336,53 +169,31 @@ with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
|
| 336 |
clean_report_out = gr.Textbox(label="📊 Rapport de nettoyage",
|
| 337 |
lines=16, interactive=False)
|
| 338 |
|
| 339 |
-
# ══════════ ONGLET 2 :
|
| 340 |
-
with gr.Tab("
|
| 341 |
gr.Markdown(
|
| 342 |
-
"Charge un CSV
|
| 343 |
-
"**
|
| 344 |
-
"
|
|
|
|
|
|
|
| 345 |
)
|
| 346 |
with gr.Row():
|
| 347 |
-
with gr.Column(scale=2):
|
| 348 |
-
csv_in = gr.File(label="CSV fournisseur", file_types=[".csv", ".tsv", ".txt"])
|
| 349 |
-
map_info = gr.Textbox(label="Colonnes détectées", interactive=False, lines=1)
|
| 350 |
-
gr.Markdown("**Mapping des colonnes** (rempli automatiquement, ajuste si besoin)")
|
| 351 |
-
col_ref = gr.Dropdown(label="Colonne Référence (Code article) *", choices=[])
|
| 352 |
-
col_lib = gr.Dropdown(label="Colonne Libellé (sert à classer la famille) *", choices=[])
|
| 353 |
-
col_prix = gr.Dropdown(label="Colonne Prix HT conseillé", choices=[NONE_COL], value=NONE_COL)
|
| 354 |
-
col_unite = gr.Dropdown(label="Colonne Unité (laissée telle quelle)", choices=[NONE_COL], value=NONE_COL)
|
| 355 |
-
|
| 356 |
with gr.Column(scale=1):
|
| 357 |
-
gr.
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
datatype=["str"] * len(COLS_ARTICLES_EBP),
|
| 372 |
-
col_count=(len(COLS_ARTICLES_EBP), "fixed"),
|
| 373 |
-
type="pandas",
|
| 374 |
-
interactive=True,
|
| 375 |
-
static_columns=[0], # « Code article » verrouillé (clé d'appariement)
|
| 376 |
-
wrap=True,
|
| 377 |
-
visible=False,
|
| 378 |
-
label="Échantillon — colonnes éditables, sauf « Code article »",
|
| 379 |
-
)
|
| 380 |
-
btn_csv_export = gr.Button("📦 Exporter par famille", variant="primary", size="lg")
|
| 381 |
-
csv_state = gr.State()
|
| 382 |
-
|
| 383 |
-
with gr.Row():
|
| 384 |
-
csv_zip = gr.File(label="📦 Télécharger les CSV EBP (ZIP)")
|
| 385 |
-
csv_report = gr.Textbox(label="📊 Rapport", lines=16, interactive=False)
|
| 386 |
|
| 387 |
# ── Événements ────────────────────────────────────────────────────────────
|
| 388 |
btn_clean.click(
|
|
@@ -392,24 +203,10 @@ with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
|
| 392 |
outputs=[clean_file_out, clean_report_out],
|
| 393 |
)
|
| 394 |
|
| 395 |
-
|
| 396 |
-
fn=
|
| 397 |
-
inputs=[
|
| 398 |
-
outputs=[
|
| 399 |
-
)
|
| 400 |
-
|
| 401 |
-
btn_csv_preview.click(
|
| 402 |
-
fn=run_csv_preview,
|
| 403 |
-
inputs=[csv_in, col_ref, col_lib, col_prix, col_unite,
|
| 404 |
-
csv_fourn_code, csv_remise, csv_taux_tva, csv_prix_ttc,
|
| 405 |
-
csv_analyse, csv_classif],
|
| 406 |
-
outputs=[csv_state, csv_preview_table, csv_preview_info],
|
| 407 |
-
)
|
| 408 |
-
|
| 409 |
-
btn_csv_export.click(
|
| 410 |
-
fn=run_csv_export,
|
| 411 |
-
inputs=[csv_state, csv_preview_table],
|
| 412 |
-
outputs=[csv_zip, csv_report],
|
| 413 |
)
|
| 414 |
|
| 415 |
|
|
|
|
| 18 |
from dotenv import load_dotenv
|
| 19 |
|
| 20 |
from core.cleaner import clean_csv
|
| 21 |
+
from core.zone_split import split_into_zones, write_zones
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
load_dotenv()
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 27 |
# ONGLET 1 — Nettoyeur CSV
|
| 28 |
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 78 |
+
# ONGLET 2 — Découpage en zones
|
| 79 |
# ══════════════════════════════════════════════════════════════════════════════
|
| 80 |
|
| 81 |
+
def _format_zone_report(rapport: dict) -> str:
|
| 82 |
+
sep_lbl = {"\t": "tabulation", ";": ";", ",": ",", "|": "|"}.get(
|
| 83 |
+
rapport.get("delimiteur", ";"), rapport.get("delimiteur", ";"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
lines = [
|
| 85 |
+
"═══ DÉCOUPAGE EN ZONES ═══",
|
| 86 |
+
f"Séparateur de colonnes : {sep_lbl}",
|
| 87 |
+
f"Lignes lues : {rapport.get('lignes_totales', 0)}",
|
| 88 |
+
f"Zones créées : {rapport.get('nb_zones', 0)}",
|
| 89 |
+
"",
|
| 90 |
+
"Détail (renomme les fichiers à ta main) :",
|
| 91 |
]
|
| 92 |
+
for z in rapport.get("zones", []):
|
| 93 |
+
sep = z["separateur"] or "(début de fichier)"
|
| 94 |
+
lines.append(f" • zone_{z['index']:02d}.csv ← « {sep} » ({z['lignes']} ligne(s))")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
return "\n".join(lines)
|
| 96 |
|
| 97 |
|
| 98 |
+
def _zones_to_preview(zones: list[dict]) -> list[list[str]]:
|
| 99 |
+
"""Tableau récap des zones détectées : n° · séparateur · nb lignes."""
|
| 100 |
+
return [
|
| 101 |
+
[f"zone_{z['index']:02d}.csv", z["separateur"] or "(début de fichier)", str(len(z["rows"]))]
|
| 102 |
+
for z in zones
|
| 103 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
|
|
|
| 105 |
|
| 106 |
+
def run_zone_split(csv_file, progress=gr.Progress()):
|
|
|
|
|
|
|
| 107 |
if csv_file is None:
|
| 108 |
+
return None, gr.update(value=None, visible=False), "⚠️ Aucun fichier CSV fourni."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
try:
|
| 110 |
progress(0.2, desc="Lecture du CSV…")
|
| 111 |
+
zones, rapport = split_into_zones(csv_file.name)
|
| 112 |
+
if not zones:
|
| 113 |
+
return None, gr.update(value=None, visible=False), "⚠️ Aucune zone détectée dans ce CSV."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
progress(0.6, desc="Écriture des zones…")
|
| 116 |
+
out_dir = tempfile.mkdtemp(prefix="zones_")
|
| 117 |
+
files = write_zones(zones, out_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
rapport_txt = _format_zone_report(rapport)
|
| 120 |
+
rapport_path = os.path.join(out_dir, "rapport_zones.txt")
|
| 121 |
+
Path(rapport_path).write_text(rapport_txt, encoding="utf-8")
|
| 122 |
+
|
| 123 |
+
zip_path = os.path.join(out_dir, "zones.zip")
|
| 124 |
+
with zipfile.ZipFile(zip_path, "w") as zf:
|
| 125 |
+
for name, path in files.items():
|
| 126 |
+
zf.write(path, name)
|
| 127 |
+
zf.write(rapport_path, "rapport_zones.txt")
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
progress(1.0, desc="Terminé !")
|
| 130 |
+
recap = _zones_to_preview(zones)
|
| 131 |
+
return zip_path, gr.update(value=recap, visible=True), rapport_txt
|
| 132 |
except Exception as exc:
|
| 133 |
tb = traceback.format_exc()
|
| 134 |
+
return None, gr.update(value=None, visible=False), f"❌ Erreur : {exc}\n\n{tb[-600:]}"
|
| 135 |
|
| 136 |
|
| 137 |
# ══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 169 |
clean_report_out = gr.Textbox(label="📊 Rapport de nettoyage",
|
| 170 |
lines=16, interactive=False)
|
| 171 |
|
| 172 |
+
# ══════════ ONGLET 2 : Découpage en zones ══════════
|
| 173 |
+
with gr.Tab("✂️ Découper en zones"):
|
| 174 |
gr.Markdown(
|
| 175 |
+
"Charge un CSV : à **chaque séparation** (ligne vide) ou **décalage de "
|
| 176 |
+
"données** (titre de section qui change la structure des colonnes), le "
|
| 177 |
+
"fichier est **coupé** et tout ce qui suit part dans un nouveau CSV. "
|
| 178 |
+
"Les fichiers sortent numérotés (`zone_01.csv`…) — tu leur donnes "
|
| 179 |
+
"l'intitulé toi-même. Les valeurs sont reprises telles quelles."
|
| 180 |
)
|
| 181 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
with gr.Column(scale=1):
|
| 183 |
+
zone_in = gr.File(label="CSV à découper", file_types=[".csv", ".tsv", ".txt"])
|
| 184 |
+
btn_zone = gr.Button("✂️ Découper en zones", variant="primary", size="lg")
|
| 185 |
+
zone_zip = gr.File(label="📦 Télécharger les zones (ZIP)")
|
| 186 |
+
with gr.Column(scale=2):
|
| 187 |
+
zone_table = gr.Dataframe(
|
| 188 |
+
headers=["Fichier", "Séparateur détecté", "Lignes"],
|
| 189 |
+
datatype=["str", "str", "str"],
|
| 190 |
+
col_count=(3, "fixed"),
|
| 191 |
+
interactive=False,
|
| 192 |
+
wrap=True,
|
| 193 |
+
visible=False,
|
| 194 |
+
label="Zones détectées",
|
| 195 |
+
)
|
| 196 |
+
zone_report = gr.Textbox(label="📊 Rapport de découpage", lines=14, interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
# ── Événements ────────────────────────────────────────────────────────────
|
| 199 |
btn_clean.click(
|
|
|
|
| 203 |
outputs=[clean_file_out, clean_report_out],
|
| 204 |
)
|
| 205 |
|
| 206 |
+
btn_zone.click(
|
| 207 |
+
fn=run_zone_split,
|
| 208 |
+
inputs=[zone_in],
|
| 209 |
+
outputs=[zone_zip, zone_table, zone_report],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
)
|
| 211 |
|
| 212 |
|
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Découpage d'un CSV en ZONES.
|
| 3 |
+
|
| 4 |
+
Principe : on lit TOUTES les lignes du CSV (sans en ignorer aucune, contrairement
|
| 5 |
+
à pandas qui saute les lignes mal formées). Chaque fois qu'une ligne marque une
|
| 6 |
+
rupture — une SÉPARATION (ligne vide) ou un DÉCALAGE de données (ligne de titre de
|
| 7 |
+
section dont la structure de colonnes diffère des lignes de données) — on coupe :
|
| 8 |
+
tout ce qui suit forme une nouvelle zone, écrite dans son propre CSV.
|
| 9 |
+
|
| 10 |
+
Les fichiers sortent numérotés (zone_01.csv, zone_02.csv…) ; l'utilisateur leur
|
| 11 |
+
donne lui-même un intitulé. Le rapport indique le séparateur de chaque zone.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import csv
|
| 16 |
+
import io
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
from core.cleaner import detect_delimiter, detect_encoding
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _filled(row: list[str]) -> int:
|
| 24 |
+
return sum(1 for c in row if str(c).strip())
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _read_rows(path: str) -> tuple[list[list[str]], str]:
|
| 28 |
+
"""Lit toutes les lignes brutes du CSV (aucune ligne ignorée)."""
|
| 29 |
+
raw = Path(path).read_bytes()
|
| 30 |
+
text, _enc = detect_encoding(raw)
|
| 31 |
+
delim = detect_delimiter(text)
|
| 32 |
+
reader = csv.reader(io.StringIO(text), delimiter=delim if delim != "\x00" else ";")
|
| 33 |
+
return [list(r) for r in reader], (delim if delim != "\x00" else ";")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _pick_header(rows: list[list[str]]) -> int:
|
| 37 |
+
"""Index de la ligne d'en-tête = première ligne avec au moins 2 cellules remplies."""
|
| 38 |
+
for i, r in enumerate(rows):
|
| 39 |
+
if _filled(r) >= 2:
|
| 40 |
+
return i
|
| 41 |
+
return 0
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_separator(row: list[str], header_len: int) -> bool:
|
| 45 |
+
"""
|
| 46 |
+
Vrai si la ligne marque une rupture de zone :
|
| 47 |
+
- ligne entièrement vide (séparation), ou
|
| 48 |
+
- une seule cellule remplie alors que l'en-tête a ≥3 colonnes (titre de section), ou
|
| 49 |
+
- nombre de cellules différent de l'en-tête (décalage de données).
|
| 50 |
+
"""
|
| 51 |
+
f = _filled(row)
|
| 52 |
+
if f == 0:
|
| 53 |
+
return True
|
| 54 |
+
if f == 1 and header_len >= 3:
|
| 55 |
+
return True
|
| 56 |
+
if len(row) != header_len and f >= 1:
|
| 57 |
+
return True
|
| 58 |
+
return False
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _label(row: list[str]) -> str:
|
| 62 |
+
"""Texte du séparateur = concaténation de ses cellules non vides."""
|
| 63 |
+
parts = [str(c).strip() for c in row if str(c).strip()]
|
| 64 |
+
return " ".join(parts)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def split_into_zones(path: str) -> tuple[list[dict], dict]:
|
| 68 |
+
"""
|
| 69 |
+
Découpe le CSV en zones.
|
| 70 |
+
|
| 71 |
+
Retourne (zones, rapport).
|
| 72 |
+
zones = [{"index", "separateur", "header", "rows"}], une entrée par zone non vide.
|
| 73 |
+
rapport = {"delimiteur", "lignes_totales", "header", "nb_zones", "zones": [...]}
|
| 74 |
+
"""
|
| 75 |
+
rows, delim = _read_rows(path)
|
| 76 |
+
if not rows:
|
| 77 |
+
return [], {"delimiteur": delim, "lignes_totales": 0, "header": [],
|
| 78 |
+
"nb_zones": 0, "zones": []}
|
| 79 |
+
|
| 80 |
+
h_idx = _pick_header(rows)
|
| 81 |
+
header = rows[h_idx]
|
| 82 |
+
header_len = len(header)
|
| 83 |
+
|
| 84 |
+
zones: list[dict] = []
|
| 85 |
+
current_label = "" # zone initiale (avant tout séparateur)
|
| 86 |
+
current_rows: list[list[str]] = []
|
| 87 |
+
|
| 88 |
+
def _flush():
|
| 89 |
+
if current_rows:
|
| 90 |
+
zones.append({
|
| 91 |
+
"index": len(zones) + 1,
|
| 92 |
+
"separateur": current_label,
|
| 93 |
+
"header": header,
|
| 94 |
+
"rows": list(current_rows),
|
| 95 |
+
})
|
| 96 |
+
|
| 97 |
+
for r in rows[h_idx + 1:]:
|
| 98 |
+
if is_separator(r, header_len):
|
| 99 |
+
# rupture : on clôt la zone courante et on démarre la suivante
|
| 100 |
+
_flush()
|
| 101 |
+
current_label = _label(r)
|
| 102 |
+
current_rows = []
|
| 103 |
+
else:
|
| 104 |
+
current_rows.append(r)
|
| 105 |
+
_flush()
|
| 106 |
+
|
| 107 |
+
rapport = {
|
| 108 |
+
"delimiteur": delim,
|
| 109 |
+
"lignes_totales": len(rows),
|
| 110 |
+
"header": header,
|
| 111 |
+
"nb_zones": len(zones),
|
| 112 |
+
"zones": [
|
| 113 |
+
{"index": z["index"], "separateur": z["separateur"], "lignes": len(z["rows"])}
|
| 114 |
+
for z in zones
|
| 115 |
+
],
|
| 116 |
+
}
|
| 117 |
+
return zones, rapport
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def write_zones(zones: list[dict], output_dir: str) -> dict[str, str]:
|
| 121 |
+
"""
|
| 122 |
+
Écrit une zone par fichier : zone_01.csv, zone_02.csv…
|
| 123 |
+
En-tête répété en tête de chaque fichier ; colonnes d'origine préservées.
|
| 124 |
+
Sortie EBP-friendly : séparateur ';', utf-8-sig, fin de ligne CRLF.
|
| 125 |
+
Retourne {nom_fichier: chemin}.
|
| 126 |
+
"""
|
| 127 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 128 |
+
produced: dict[str, str] = {}
|
| 129 |
+
for z in zones:
|
| 130 |
+
fname = f"zone_{z['index']:02d}.csv"
|
| 131 |
+
path = os.path.join(output_dir, fname)
|
| 132 |
+
with open(path, "w", newline="", encoding="utf-8-sig") as f:
|
| 133 |
+
w = csv.writer(f, delimiter=";", lineterminator="\r\n")
|
| 134 |
+
w.writerow(z["header"])
|
| 135 |
+
w.writerows(z["rows"])
|
| 136 |
+
produced[fname] = path
|
| 137 |
+
return produced
|
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests du découpage en zones (core.zone_split)."""
|
| 2 |
+
import csv
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
|
| 6 |
+
from core.zone_split import split_into_zones, write_zones, is_separator
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
SAMPLE = (
|
| 10 |
+
"Ref;Designation;Prix;Unite\r\n"
|
| 11 |
+
"A1;Article 1;10;ml\r\n"
|
| 12 |
+
"A2;Article 2;20;M\r\n"
|
| 13 |
+
"VELOURS COLLECTION\r\n" # décalage : 1 cellule → séparateur
|
| 14 |
+
"B1;Article 3;30;U\r\n"
|
| 15 |
+
";;;\r\n" # ligne vide → séparateur
|
| 16 |
+
"C1;Article 4;40;m²\r\n"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _write(tmp_path, content=SAMPLE, name="in.csv"):
|
| 21 |
+
p = os.path.join(tmp_path, name)
|
| 22 |
+
with open(p, "w", encoding="utf-8-sig", newline="") as f:
|
| 23 |
+
f.write(content)
|
| 24 |
+
return p
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ── Détection séparateur ──────────────────────────────────────────────────────
|
| 28 |
+
|
| 29 |
+
def test_is_separator_blank():
|
| 30 |
+
assert is_separator(["", "", "", ""], 4) is True
|
| 31 |
+
|
| 32 |
+
def test_is_separator_titre_une_cellule():
|
| 33 |
+
assert is_separator(["VELOURS"], 4) is True
|
| 34 |
+
|
| 35 |
+
def test_is_separator_decalage_colonnes():
|
| 36 |
+
assert is_separator(["a", "b"], 4) is True
|
| 37 |
+
|
| 38 |
+
def test_is_separator_ligne_data_normale():
|
| 39 |
+
assert is_separator(["A1", "Article", "10", "ml"], 4) is False
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ── Découpage ─────────────────────────────────────────────────────────────────
|
| 43 |
+
|
| 44 |
+
def test_trois_zones():
|
| 45 |
+
with tempfile.TemporaryDirectory() as d:
|
| 46 |
+
zones, rapport = split_into_zones(_write(d))
|
| 47 |
+
assert rapport["nb_zones"] == 3
|
| 48 |
+
assert [len(z["rows"]) for z in zones] == [2, 1, 1]
|
| 49 |
+
|
| 50 |
+
def test_separateurs_nommes():
|
| 51 |
+
with tempfile.TemporaryDirectory() as d:
|
| 52 |
+
zones, _ = split_into_zones(_write(d))
|
| 53 |
+
assert zones[0]["separateur"] == "" # début de fichier
|
| 54 |
+
assert zones[1]["separateur"] == "VELOURS COLLECTION"
|
| 55 |
+
assert zones[2]["separateur"] == "" # après ligne vide
|
| 56 |
+
|
| 57 |
+
def test_write_zones_fichiers_numerotes():
|
| 58 |
+
with tempfile.TemporaryDirectory() as d:
|
| 59 |
+
zones, _ = split_into_zones(_write(d))
|
| 60 |
+
files = write_zones(zones, d)
|
| 61 |
+
assert set(files) == {"zone_01.csv", "zone_02.csv", "zone_03.csv"}
|
| 62 |
+
|
| 63 |
+
def test_write_zones_header_repete_et_valeurs_preservees():
|
| 64 |
+
with tempfile.TemporaryDirectory() as d:
|
| 65 |
+
zones, _ = split_into_zones(_write(d))
|
| 66 |
+
files = write_zones(zones, d)
|
| 67 |
+
with open(files["zone_03.csv"], encoding="utf-8-sig") as f:
|
| 68 |
+
rows = list(csv.reader(f, delimiter=";"))
|
| 69 |
+
assert rows[0] == ["Ref", "Designation", "Prix", "Unite"] # header répété
|
| 70 |
+
assert rows[1] == ["C1", "Article 4", "40", "m²"] # unité préservée
|
| 71 |
+
|
| 72 |
+
def test_csv_vide():
|
| 73 |
+
with tempfile.TemporaryDirectory() as d:
|
| 74 |
+
zones, rapport = split_into_zones(_write(d, content="", name="empty.csv"))
|
| 75 |
+
assert zones == []
|
| 76 |
+
assert rapport["nb_zones"] == 0
|