Spaces:
Sleeping
Sleeping
feat: page unique à onglets (Nettoyeur CSV + Extracteur PDF) servie sur /
Browse filesLes deux outils sont maintenant sur la MÊME page :
- app_gradio.py : gr.Tabs avec onglet « 🧹 Nettoyeur CSV » (core.cleaner)
et onglet « 📄 Extracteur PDF → CSV EBP » (sous-familles + aperçu éditable)
- app.py : FastAPI minimal (/ping) + Gradio monté à la racine via
gr.mount_gradio_app(app, demo, path="/"). Fini le /extracteur séparé.
Le nettoyeur n'utilise plus les endpoints REST /clean /download : tout passe
par l'UI Gradio. 66 tests verts (core.cleaner + extracteur inchangés).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- app.py +17 -125
- app_gradio.py +179 -91
app.py
CHANGED
|
@@ -1,137 +1,29 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import time
|
| 4 |
-
import traceback
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from fastapi.staticfiles import StaticFiles
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
|
| 14 |
-
app.add_middleware(
|
| 15 |
-
CORSMiddleware,
|
| 16 |
-
allow_origins=["*"],
|
| 17 |
-
allow_methods=["*"],
|
| 18 |
-
allow_headers=["*"],
|
| 19 |
-
)
|
| 20 |
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 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")
|
| 40 |
async def 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 |
-
|
| 136 |
-
|
| 137 |
-
print(f"[extracteur] UI Gradio non montée : {type(exc).__name__}: {exc}")
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Point d'entrée du Space : FastAPI minimal + UI Gradio à onglets servie sur /.
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
Une seule page, deux onglets :
|
| 5 |
+
- 🧹 Nettoyeur CSV (core.cleaner — 100 % local, sans IA)
|
| 6 |
+
- 📄 Extracteur PDF → EBP (core.agent/subfamily — analyse sous-familles + aperçu éditable)
|
|
|
|
| 7 |
|
| 8 |
+
Lancement (Docker) : uvicorn app:app --host 0.0.0.0 --port 7860
|
| 9 |
+
"""
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
from fastapi import FastAPI
|
| 12 |
+
from fastapi.responses import JSONResponse
|
| 13 |
|
| 14 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
from app_gradio import demo
|
| 17 |
|
| 18 |
+
load_dotenv()
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
app = FastAPI(title="Atelier EBP — Nettoyeur CSV + Extracteur PDF")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
@app.get("/ping")
|
| 24 |
async def ping():
|
| 25 |
+
return JSONResponse({"ok": True})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
# UI Gradio (les deux onglets) montée à la racine.
|
| 29 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
|
|
app_gradio.py
CHANGED
|
@@ -22,6 +22,7 @@ from core.csv_writer import (
|
|
| 22 |
export_ebp, export_articles_par_famille,
|
| 23 |
COLS_ARTICLES_EBP, _build_article_ebp_row,
|
| 24 |
)
|
|
|
|
| 25 |
from core.extractor import debug_layout
|
| 26 |
from core.profil import list_profiles, load_profile, save_profile
|
| 27 |
from core.subfamily import analyse_sous_familles
|
|
@@ -482,109 +483,189 @@ def refresh_profiles():
|
|
| 482 |
return gr.update(choices=choices, value="(aucun)")
|
| 483 |
|
| 484 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
# ── Interface Gradio ──────────────────────────────────────────────────────────
|
| 486 |
|
| 487 |
-
with gr.Blocks(title="
|
| 488 |
-
gr.Markdown("#
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
"(familles → fournisseur → articles). Les prix ne sont jamais inventés : "
|
| 492 |
-
"chaque valeur est tracée au texte source."
|
| 493 |
-
)
|
| 494 |
|
| 495 |
-
|
| 496 |
-
with gr.
|
| 497 |
-
gr.Markdown("
|
| 498 |
-
|
| 499 |
with gr.Row():
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
with gr.Row():
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
|
| 508 |
-
with gr.Column(scale=2):
|
| 509 |
-
gr.Markdown("### 🏭 Fournisseur")
|
| 510 |
with gr.Row():
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
)
|
| 527 |
-
profil_save_nom = gr.Textbox(label="Sauvegarder ce profil sous…",
|
| 528 |
-
placeholder="laisser vide pour ne pas sauvegarder")
|
| 529 |
-
|
| 530 |
-
with gr.Column(scale=1):
|
| 531 |
-
gr.Markdown("### ⚙️ Paramètres")
|
| 532 |
-
remise_input = gr.Slider(0, 80, value=45, step=1, label="Remise fournisseur (%)")
|
| 533 |
-
prix_ttc_toggle = gr.Checkbox(label="Les prix du catalogue sont TTC", value=False)
|
| 534 |
-
taux_tva = gr.Radio([l for l, _ in TVA_CHOICES], value="20 %", label="Taux TVA (si prix TTC)")
|
| 535 |
-
unite_def = gr.Dropdown(UNITE_CHOICES, value="ml", label="Unité par défaut")
|
| 536 |
-
regex_config_input = gr.Textbox(
|
| 537 |
-
label="Extracteur regex (JSON optionnel — prioritaire sur le LLM)",
|
| 538 |
-
placeholder='{"pattern_ligne": "...", "group_nom": 1, ...}',
|
| 539 |
-
lines=3,
|
| 540 |
-
)
|
| 541 |
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
|
|
|
|
|
|
|
|
|
| 557 |
)
|
|
|
|
| 558 |
|
| 559 |
-
|
| 560 |
-
btn_preview = gr.Button("👁️ Aperçu éditable (10 réf.)", variant="secondary", size="lg")
|
| 561 |
-
btn_convert = gr.Button("▶️ Convertir directement (sans aperçu)", variant="primary", size="lg")
|
| 562 |
-
|
| 563 |
-
# ── Aperçu éditable avant export ─────────────────────────────────────────
|
| 564 |
-
gr.Markdown("### ✏️ Aperçu éditable — corrige avant l'export")
|
| 565 |
-
preview_info = gr.Textbox(label="Aperçu", interactive=False, lines=2)
|
| 566 |
-
preview_table = gr.Dataframe(
|
| 567 |
-
headers=COLS_ARTICLES_EBP,
|
| 568 |
-
datatype=["str"] * len(COLS_ARTICLES_EBP),
|
| 569 |
-
col_count=(len(COLS_ARTICLES_EBP), "fixed"),
|
| 570 |
-
type="pandas",
|
| 571 |
-
interactive=True,
|
| 572 |
-
# « Code article » (clé d'appariement) verrouillé ; colonnes éditables.
|
| 573 |
-
static_columns=[0],
|
| 574 |
-
wrap=True,
|
| 575 |
-
visible=False,
|
| 576 |
-
label="Échantillon — colonnes éditables, sauf « Code article »",
|
| 577 |
-
)
|
| 578 |
-
btn_export = gr.Button("📦 Exporter l'aperçu validé", variant="primary", size="lg")
|
| 579 |
-
|
| 580 |
-
preview_state = gr.State()
|
| 581 |
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
|
| 586 |
-
|
| 587 |
-
|
| 588 |
|
| 589 |
_convert_inputs = [
|
| 590 |
pdf_input, page_from, page_to,
|
|
@@ -597,6 +678,13 @@ with gr.Blocks(title="PDF → CSV EBP", theme=gr.themes.Soft()) as demo:
|
|
| 597 |
]
|
| 598 |
|
| 599 |
# ── Événements ──────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
btn_debug.click(
|
| 601 |
fn=run_debug_layout,
|
| 602 |
inputs=[pdf_input, page_from, page_to],
|
|
|
|
| 22 |
export_ebp, export_articles_par_famille,
|
| 23 |
COLS_ARTICLES_EBP, _build_article_ebp_row,
|
| 24 |
)
|
| 25 |
+
from core.cleaner import clean_csv
|
| 26 |
from core.extractor import debug_layout
|
| 27 |
from core.profil import list_profiles, load_profile, save_profile
|
| 28 |
from core.subfamily import analyse_sous_familles
|
|
|
|
| 483 |
return gr.update(choices=choices, value="(aucun)")
|
| 484 |
|
| 485 |
|
| 486 |
+
# ── Nettoyeur CSV (onglet) ────────────────────────────────────────────────────
|
| 487 |
+
|
| 488 |
+
def _format_clean_report(report: dict) -> str:
|
| 489 |
+
lines = [
|
| 490 |
+
"═══ RAPPORT DE NETTOYAGE ═══",
|
| 491 |
+
f"Encodage détecté : {report.get('encodage_detecte')}",
|
| 492 |
+
f"Séparateur détecté : {report.get('separateur_detecte')}",
|
| 493 |
+
f"Lignes : {report.get('lignes_initiales')} → {report.get('lignes_finales')}",
|
| 494 |
+
f"Colonnes : {report.get('colonnes_initiales')} → {report.get('colonnes_finales')}",
|
| 495 |
+
f"Sortie : séparateur '{report.get('separateur_sortie')}' / {report.get('encodage_sortie')}",
|
| 496 |
+
"",
|
| 497 |
+
"Actions :",
|
| 498 |
+
]
|
| 499 |
+
for a in report.get("actions", []):
|
| 500 |
+
lines.append(f" • {a}")
|
| 501 |
+
return "\n".join(lines)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def run_clean(csv_file, drop_empty, drop_duplicates, trim_whitespace,
|
| 505 |
+
normalize_headers, remove_symbols, keep_digits_only,
|
| 506 |
+
decimal_comma, ebp_format):
|
| 507 |
+
if csv_file is None:
|
| 508 |
+
return None, "⚠️ Aucun fichier CSV fourni."
|
| 509 |
+
try:
|
| 510 |
+
raw = Path(csv_file.name).read_bytes()
|
| 511 |
+
except Exception as exc:
|
| 512 |
+
return None, f"❌ Lecture impossible : {exc}"
|
| 513 |
+
if not raw.strip():
|
| 514 |
+
return None, "⚠️ Le fichier est vide."
|
| 515 |
+
|
| 516 |
+
options = {
|
| 517 |
+
"drop_empty": drop_empty, "drop_duplicates": drop_duplicates,
|
| 518 |
+
"trim_whitespace": trim_whitespace, "normalize_headers": normalize_headers,
|
| 519 |
+
"remove_symbols": remove_symbols, "keep_digits_only": keep_digits_only,
|
| 520 |
+
"decimal_comma": decimal_comma, "ebp_format": ebp_format,
|
| 521 |
+
}
|
| 522 |
+
try:
|
| 523 |
+
cleaned, report = clean_csv(raw, options)
|
| 524 |
+
except Exception as exc:
|
| 525 |
+
tb = traceback.format_exc()
|
| 526 |
+
return None, f"❌ Erreur : {exc}\n\n{tb[-500:]}"
|
| 527 |
+
|
| 528 |
+
base = Path(csv_file.name).stem or "fichier"
|
| 529 |
+
out_dir = tempfile.mkdtemp(prefix="csv_clean_")
|
| 530 |
+
out_path = os.path.join(out_dir, f"{base}_nettoye.csv")
|
| 531 |
+
Path(out_path).write_bytes(cleaned)
|
| 532 |
+
return out_path, _format_clean_report(report)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
# ── Interface Gradio ──────────────────────────────────────────────────────────
|
| 536 |
|
| 537 |
+
with gr.Blocks(title="Atelier — Outils EBP", theme=gr.themes.Soft()) as demo:
|
| 538 |
+
gr.Markdown("# 🧰 Atelier — Outils CSV / PDF pour EBP Gestion Commerciale")
|
| 539 |
+
|
| 540 |
+
with gr.Tabs():
|
|
|
|
|
|
|
|
|
|
| 541 |
|
| 542 |
+
# ══════════ ONGLET 1 : Nettoyeur CSV ══════════
|
| 543 |
+
with gr.Tab("🧹 Nettoyeur CSV"):
|
| 544 |
+
gr.Markdown("Charge un CSV, choisis le nettoyage, récupère un fichier propre. "
|
| 545 |
+
"100 % local, sans IA ni clé API.")
|
| 546 |
with gr.Row():
|
| 547 |
+
with gr.Column(scale=2):
|
| 548 |
+
clean_input = gr.File(label="Fichier CSV / TSV / TXT",
|
| 549 |
+
file_types=[".csv", ".tsv", ".txt"])
|
| 550 |
+
with gr.Row():
|
| 551 |
+
opt_drop_empty = gr.Checkbox(label="Supprimer lignes/colonnes vides", value=True)
|
| 552 |
+
opt_drop_dup = gr.Checkbox(label="Supprimer les doublons", value=True)
|
| 553 |
+
with gr.Row():
|
| 554 |
+
opt_trim = gr.Checkbox(label="Espaces superflus", value=True)
|
| 555 |
+
opt_headers = gr.Checkbox(label="Normaliser les en-têtes", value=True)
|
| 556 |
+
with gr.Row():
|
| 557 |
+
opt_remove_sym = gr.Checkbox(label="Retirer les symboles (€ % # *…)", value=False)
|
| 558 |
+
opt_digits = gr.Checkbox(label="Garder uniquement les chiffres", value=False)
|
| 559 |
+
with gr.Row():
|
| 560 |
+
opt_decimal = gr.Checkbox(label="Décimales en virgule FR", value=False)
|
| 561 |
+
opt_ebp = gr.Checkbox(label="Format EBP ( ; / utf-8-sig )", value=False)
|
| 562 |
+
btn_clean = gr.Button("🧹 Nettoyer", variant="primary", size="lg")
|
| 563 |
+
with gr.Column(scale=2):
|
| 564 |
+
clean_file_out = gr.File(label="📥 CSV nettoyé")
|
| 565 |
+
clean_report_out = gr.Textbox(label="📊 Rapport de nettoyage",
|
| 566 |
+
lines=16, interactive=False)
|
| 567 |
+
|
| 568 |
+
# ══════════ ONGLET 2 : Extracteur PDF → CSV EBP ══════════
|
| 569 |
+
with gr.Tab("📄 Extracteur PDF → CSV EBP"):
|
| 570 |
+
gr.Markdown(
|
| 571 |
+
"Convertit un catalogue fournisseur PDF en CSV EBP "
|
| 572 |
+
"(familles → fournisseur → articles), avec analyse des sous-familles. "
|
| 573 |
+
"Les prix ne sont jamais inventés : chaque valeur est tracée au texte source."
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
with gr.Row():
|
| 577 |
+
with gr.Column(scale=2):
|
| 578 |
+
gr.Markdown("### 📁 Fichier & pages")
|
| 579 |
+
pdf_input = gr.File(label="Catalogue PDF", file_types=[".pdf"])
|
| 580 |
+
with gr.Row():
|
| 581 |
+
page_from = gr.Slider(1, 500, value=1, step=1, label="Page début")
|
| 582 |
+
page_to = gr.Slider(1, 500, value=50, step=1, label="Page fin")
|
| 583 |
+
sample_mode = gr.Checkbox(label="Mode échantillon (30 premières lignes)", value=False)
|
| 584 |
+
with gr.Row():
|
| 585 |
+
btn_debug = gr.Button("🔍 Analyser la structure du PDF", size="sm")
|
| 586 |
+
debug_output = gr.Textbox(label="Structure par page (tables / lignes / prix)", lines=8,
|
| 587 |
+
interactive=False, visible=False)
|
| 588 |
+
|
| 589 |
+
with gr.Column(scale=2):
|
| 590 |
+
gr.Markdown("### 🏭 Fournisseur")
|
| 591 |
+
with gr.Row():
|
| 592 |
+
profil_dropdown = gr.Dropdown(
|
| 593 |
+
choices=["(aucun)"] + list_profiles(),
|
| 594 |
+
value="(aucun)",
|
| 595 |
+
label="Charger un profil",
|
| 596 |
+
interactive=True,
|
| 597 |
+
)
|
| 598 |
+
btn_refresh = gr.Button("🔄", size="sm")
|
| 599 |
+
|
| 600 |
+
fournisseur_nom = gr.Textbox(label="Nom du fournisseur *", placeholder="Ex : CASAMANCE")
|
| 601 |
+
fournisseur_code = gr.Textbox(label="Code fournisseur", placeholder="Ex : CAS001")
|
| 602 |
+
code_famille = gr.Textbox(label="Code famille EBP par défaut", value="FFR00001")
|
| 603 |
+
collection_famille_map_input = gr.Textbox(
|
| 604 |
+
label="Mapping collection → code famille EBP (JSON optionnel)",
|
| 605 |
+
placeholder='{"CHOREGRAPHIE": "TIS-DEC", "PIUMA": "TIS-VEL"}',
|
| 606 |
+
lines=2,
|
| 607 |
+
)
|
| 608 |
+
profil_save_nom = gr.Textbox(label="Sauvegarder ce profil sous…",
|
| 609 |
+
placeholder="laisser vide pour ne pas sauvegarder")
|
| 610 |
+
|
| 611 |
+
with gr.Column(scale=1):
|
| 612 |
+
gr.Markdown("### ⚙️ Paramètres")
|
| 613 |
+
remise_input = gr.Slider(0, 80, value=45, step=1, label="Remise fournisseur (%)")
|
| 614 |
+
prix_ttc_toggle = gr.Checkbox(label="Les prix du catalogue sont TTC", value=False)
|
| 615 |
+
taux_tva = gr.Radio([l for l, _ in TVA_CHOICES], value="20 %", label="Taux TVA (si prix TTC)")
|
| 616 |
+
unite_def = gr.Dropdown(UNITE_CHOICES, value="ml", label="Unité par défaut")
|
| 617 |
+
regex_config_input = gr.Textbox(
|
| 618 |
+
label="Extracteur regex (JSON optionnel — prioritaire sur le LLM)",
|
| 619 |
+
placeholder='{"pattern_ligne": "...", "group_nom": 1, ...}',
|
| 620 |
+
lines=3,
|
| 621 |
+
)
|
| 622 |
|
|
|
|
|
|
|
| 623 |
with gr.Row():
|
| 624 |
+
with gr.Column():
|
| 625 |
+
gr.Markdown("### 🗂️ Analyse des sous-familles")
|
| 626 |
+
gr.Markdown(
|
| 627 |
+
"Classe chaque article dans sa famille EBP "
|
| 628 |
+
"(TAPISSERIE · RIDEAU · MOUSSE · SELLERIE) et produit "
|
| 629 |
+
"**1 fichier CSV par famille** au format écran « Articles » EBP."
|
| 630 |
+
)
|
| 631 |
+
analyse_familles_toggle = gr.Checkbox(
|
| 632 |
+
label="Activer l'analyse des sous-familles (export par famille)",
|
| 633 |
+
value=True,
|
| 634 |
+
)
|
| 635 |
+
classif_llm_toggle = gr.Checkbox(
|
| 636 |
+
label="Affiner les cas ambigus avec Claude (sinon règles seules)",
|
| 637 |
+
value=True,
|
| 638 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
|
| 640 |
+
with gr.Row():
|
| 641 |
+
btn_preview = gr.Button("👁️ Aperçu éditable (10 réf.)", variant="secondary", size="lg")
|
| 642 |
+
btn_convert = gr.Button("▶️ Convertir directement (sans aperçu)", variant="primary", size="lg")
|
| 643 |
+
|
| 644 |
+
# ── Aperçu éditable avant export ─────────────────────────────────
|
| 645 |
+
gr.Markdown("### ✏️ Aperçu éditable — corrige avant l'export")
|
| 646 |
+
preview_info = gr.Textbox(label="Aperçu", interactive=False, lines=2)
|
| 647 |
+
preview_table = gr.Dataframe(
|
| 648 |
+
headers=COLS_ARTICLES_EBP,
|
| 649 |
+
datatype=["str"] * len(COLS_ARTICLES_EBP),
|
| 650 |
+
col_count=(len(COLS_ARTICLES_EBP), "fixed"),
|
| 651 |
+
type="pandas",
|
| 652 |
+
interactive=True,
|
| 653 |
+
# « Code article » (clé d'appariement) verrouillé ; colonnes éditables.
|
| 654 |
+
static_columns=[0],
|
| 655 |
+
wrap=True,
|
| 656 |
+
visible=False,
|
| 657 |
+
label="Échantillon — colonnes éditables, sauf « Code article »",
|
| 658 |
)
|
| 659 |
+
btn_export = gr.Button("📦 Exporter l'aperçu validé", variant="primary", size="lg")
|
| 660 |
|
| 661 |
+
preview_state = gr.State()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 662 |
|
| 663 |
+
with gr.Row():
|
| 664 |
+
zip_output = gr.File(label="📦 Télécharger les fichiers CSV (ZIP)")
|
| 665 |
+
rapport_output = gr.Textbox(label="📊 Rapport d'audit", lines=20, interactive=False)
|
| 666 |
|
| 667 |
+
anomalies_output = gr.Textbox(label="⚠️ Anomalies (prix non traçables)", lines=6, interactive=False)
|
| 668 |
+
err_output = gr.Textbox(label="Erreur", visible=False)
|
| 669 |
|
| 670 |
_convert_inputs = [
|
| 671 |
pdf_input, page_from, page_to,
|
|
|
|
| 678 |
]
|
| 679 |
|
| 680 |
# ── Événements ──────────────────────────────────────────────────────────
|
| 681 |
+
btn_clean.click(
|
| 682 |
+
fn=run_clean,
|
| 683 |
+
inputs=[clean_input, opt_drop_empty, opt_drop_dup, opt_trim, opt_headers,
|
| 684 |
+
opt_remove_sym, opt_digits, opt_decimal, opt_ebp],
|
| 685 |
+
outputs=[clean_file_out, clean_report_out],
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
btn_debug.click(
|
| 689 |
fn=run_debug_layout,
|
| 690 |
inputs=[pdf_input, page_from, page_to],
|