Stephan86 Claude Sonnet 4.6 commited on
Commit
b7cf9e1
·
1 Parent(s): cf56ac6

feat: replace Gradio with FastAPI + custom HTML/CSS frontend

Browse files

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

Files changed (5) hide show
  1. Dockerfile +12 -0
  2. README.md +1 -3
  3. app.py +47 -55
  4. requirements.txt +3 -1
  5. static/index.html +380 -0
Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY . .
9
+
10
+ EXPOSE 7860
11
+
12
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -3,9 +3,7 @@ title: PDF CSV Agent
3
  emoji: 📄
4
  colorFrom: blue
5
  colorTo: green
6
- sdk: gradio
7
- sdk_version: 5.9.1
8
- app_file: app.py
9
  pinned: false
10
  ---
11
 
 
3
  emoji: 📄
4
  colorFrom: blue
5
  colorTo: green
6
+ sdk: docker
 
 
7
  pinned: false
8
  ---
9
 
app.py CHANGED
@@ -1,74 +1,66 @@
1
  import os
 
2
  import tempfile
3
 
4
  from dotenv import load_dotenv
5
- import gradio as gr
6
-
7
- load_dotenv()
8
 
9
  from core.extractor import extract_pages
10
  from core.agent import extract_articles
11
  from core.csv_writer import to_csv
12
 
 
13
 
14
- def process(pdf_file, page_from, page_to, margin_pct, default_unit):
15
- if pdf_file is None:
16
- return None, "Veuillez charger un fichier PDF."
17
-
18
- p_from, p_to = int(page_from), int(page_to)
19
- if p_from > p_to:
20
- return None, "La page de début doit être ≤ à la page de fin."
21
-
22
- pages = extract_pages(pdf_file, p_from, p_to)
23
- if not pages:
24
- return None, "Aucune page extraite dans la plage indiquée."
25
-
26
- try:
27
- articles = extract_articles(pages, float(margin_pct), default_unit)
28
- except Exception as exc:
29
- return None, f"Erreur lors de l'extraction IA : {exc}"
30
-
31
- if not articles:
32
- return None, "Aucun article détecté dans ces pages."
33
 
34
- tmp = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
35
- tmp.close()
36
- to_csv(articles, tmp.name, float(margin_pct))
37
- return tmp.name, f"{len(articles)} articles extraits."
38
 
 
 
 
39
 
40
- with gr.Blocks(title="PDF → CSV", theme=gr.themes.Soft()) as demo:
41
- gr.Markdown(
42
- "## PDF → CSV\n"
43
- "Extrait les articles d'un catalogue PDF et génère un fichier CSV tarifaire prêt à l'import."
44
- )
45
 
46
- with gr.Row():
47
- pdf_input = gr.File(label="Fichier PDF", file_types=[".pdf"], type="filepath")
 
 
 
 
 
 
 
 
48
 
49
- with gr.Row():
50
- page_from = gr.Slider(minimum=1, maximum=500, value=1, step=1, label="Page de")
51
- page_to = gr.Slider(minimum=1, maximum=500, value=10, step=1, label="Page à")
52
 
53
- with gr.Row():
54
- margin_pct = gr.Number(value=30, minimum=0, maximum=100, label="Marge %")
55
- default_unit = gr.Dropdown(
56
- choices=["ML", "M²", "Pièce", "Rouleau"],
57
- value="Pièce",
58
- label="Unité par défaut",
 
 
 
 
 
 
 
 
 
 
 
 
59
  )
 
 
 
 
 
 
60
 
61
- run_btn = gr.Button("Extraire → CSV", variant="primary")
62
-
63
- with gr.Row():
64
- csv_output = gr.File(label="Télécharger le CSV")
65
- status_msg = gr.Textbox(label="Statut", interactive=False)
66
-
67
- run_btn.click(
68
- fn=process,
69
- inputs=[pdf_input, page_from, page_to, margin_pct, default_unit],
70
- outputs=[csv_output, status_msg],
71
- )
72
 
73
- if __name__ == "__main__":
74
- demo.launch()
 
1
  import os
2
+ import shutil
3
  import tempfile
4
 
5
  from dotenv import load_dotenv
6
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
7
+ from fastapi.responses import FileResponse
8
+ from fastapi.staticfiles import StaticFiles
9
 
10
  from core.extractor import extract_pages
11
  from core.agent import extract_articles
12
  from core.csv_writer import to_csv
13
 
14
+ load_dotenv()
15
 
16
+ app = FastAPI(title="PDF → CSV Agent")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
 
 
 
 
18
 
19
+ @app.get("/")
20
+ async def index():
21
+ return FileResponse("static/index.html")
22
 
 
 
 
 
 
23
 
24
+ @app.post("/extract")
25
+ async def extract(
26
+ pdf: UploadFile = File(...),
27
+ page_from: int = Form(1),
28
+ page_to: int = Form(10),
29
+ margin_pct: float = Form(30.0),
30
+ default_unit: str = Form("Pièce"),
31
+ ):
32
+ if not pdf.filename.lower().endswith(".pdf"):
33
+ raise HTTPException(status_code=400, detail="Le fichier doit être un PDF.")
34
 
35
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
36
+ shutil.copyfileobj(pdf.file, tmp)
37
+ pdf_path = tmp.name
38
 
39
+ try:
40
+ pages = extract_pages(pdf_path, page_from, page_to)
41
+ if not pages:
42
+ raise HTTPException(status_code=422, detail="Aucune page dans la plage indiquée.")
43
+
44
+ articles = extract_articles(pages, margin_pct, default_unit)
45
+ if not articles:
46
+ raise HTTPException(status_code=422, detail="Aucun article détecté.")
47
+
48
+ out = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
49
+ out.close()
50
+ to_csv(articles, out.name, margin_pct)
51
+
52
+ return FileResponse(
53
+ out.name,
54
+ filename="articles.csv",
55
+ media_type="text/csv; charset=utf-8",
56
+ headers={"X-Article-Count": str(len(articles))},
57
  )
58
+ except HTTPException:
59
+ raise
60
+ except Exception as exc:
61
+ raise HTTPException(status_code=500, detail=str(exc))
62
+ finally:
63
+ os.unlink(pdf_path)
64
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ app.mount("/static", StaticFiles(directory="static"), name="static")
 
requirements.txt CHANGED
@@ -1,5 +1,7 @@
1
  anthropic>=0.40.0
2
- gradio>=5.0.0
 
 
3
  pandas>=2.0.0
4
  PyMuPDF>=1.24.0
5
  python-dotenv>=1.0.0
 
1
  anthropic>=0.40.0
2
+ fastapi>=0.110.0
3
+ uvicorn[standard]>=0.29.0
4
+ python-multipart>=0.0.9
5
  pandas>=2.0.0
6
  PyMuPDF>=1.24.0
7
  python-dotenv>=1.0.0
static/index.html ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="fr">
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
+
10
+ :root {
11
+ --bg: #0f1117;
12
+ --surface: #1a1d27;
13
+ --border: #2a2d3e;
14
+ --accent: #6366f1;
15
+ --accent-hover: #4f46e5;
16
+ --text: #e2e8f0;
17
+ --muted: #64748b;
18
+ --success: #10b981;
19
+ --error: #ef4444;
20
+ }
21
+
22
+ body {
23
+ background: var(--bg);
24
+ color: var(--text);
25
+ font-family: system-ui, -apple-system, sans-serif;
26
+ min-height: 100vh;
27
+ display: flex;
28
+ flex-direction: column;
29
+ align-items: center;
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;
40
+ background: linear-gradient(135deg, #6366f1, #a78bfa);
41
+ -webkit-background-clip: text;
42
+ -webkit-text-fill-color: transparent;
43
+ margin-bottom: .5rem;
44
+ }
45
+ header p { color: var(--muted); font-size: 1rem; }
46
+
47
+ .card {
48
+ background: var(--surface);
49
+ border: 1px solid var(--border);
50
+ border-radius: 16px;
51
+ padding: 2rem;
52
+ width: 100%;
53
+ max-width: 680px;
54
+ }
55
+
56
+ /* Drop zone */
57
+ .drop-zone {
58
+ border: 2px dashed var(--border);
59
+ border-radius: 12px;
60
+ padding: 2.5rem 1rem;
61
+ text-align: center;
62
+ cursor: pointer;
63
+ transition: border-color .2s, background .2s;
64
+ margin-bottom: 1.5rem;
65
+ position: relative;
66
+ }
67
+ .drop-zone:hover, .drop-zone.drag-over {
68
+ border-color: var(--accent);
69
+ background: rgba(99,102,241,.06);
70
+ }
71
+ .drop-zone input[type="file"] {
72
+ position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
73
+ }
74
+ .drop-zone .icon { font-size: 2.5rem; margin-bottom: .75rem; }
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="500" 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="500" value="10" />
250
+ <span class="range-val" id="pageToVal">10</span>
251
+ </div>
252
+ </label>
253
+
254
+ <label>
255
+ Marge %
256
+ <input type="number" name="margin_pct" value="30" min="0" max="100" step="0.5" />
257
+ </label>
258
+
259
+ <label>
260
+ Unité par défaut
261
+ <select name="default_unit">
262
+ <option value="Pièce">Pièce</option>
263
+ <option value="ML">ML</option>
264
+ <option value="M²">M²</option>
265
+ <option value="Rouleau">Rouleau</option>
266
+ </select>
267
+ </label>
268
+ </div>
269
+
270
+ <button type="submit" id="submitBtn">Extraire → CSV</button>
271
+
272
+ <!-- Progress -->
273
+ <div class="progress-wrap" id="progressWrap">
274
+ <div class="progress-bar-bg"><div class="progress-bar" id="progressBar"></div></div>
275
+ <div class="progress-label" id="progressLabel">Analyse en cours…</div>
276
+ </div>
277
+
278
+ <!-- Result -->
279
+ <div class="result" id="result"></div>
280
+
281
+ </form>
282
+ </div>
283
+
284
+ <footer>
285
+ <a href="https://github.com/boutique-oss/convertionpdfcsv" target="_blank">Code source</a>
286
+ &nbsp;·&nbsp; Propulsé par Claude Sonnet
287
+ </footer>
288
+
289
+ <script>
290
+ // Sliders
291
+ const pageFrom = document.getElementById('pageFrom');
292
+ const pageTo = document.getElementById('pageTo');
293
+ const pfv = document.getElementById('pageFromVal');
294
+ const ptv = document.getElementById('pageToVal');
295
+ pageFrom.addEventListener('input', () => pfv.textContent = pageFrom.value);
296
+ pageTo.addEventListener('input', () => ptv.textContent = pageTo.value);
297
+
298
+ // Drop zone
299
+ const dropZone = document.getElementById('dropZone');
300
+ const pdfInput = document.getElementById('pdfInput');
301
+ const fileName = document.getElementById('fileName');
302
+
303
+ pdfInput.addEventListener('change', () => {
304
+ if (pdfInput.files[0]) fileName.textContent = pdfInput.files[0].name;
305
+ });
306
+ dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
307
+ dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
308
+ dropZone.addEventListener('drop', e => {
309
+ e.preventDefault();
310
+ dropZone.classList.remove('drag-over');
311
+ const f = e.dataTransfer.files[0];
312
+ if (f && f.name.endsWith('.pdf')) {
313
+ const dt = new DataTransfer();
314
+ dt.items.add(f);
315
+ pdfInput.files = dt.files;
316
+ fileName.textContent = f.name;
317
+ }
318
+ });
319
+
320
+ // Form submit
321
+ const form = document.getElementById('form');
322
+ const submitBtn = document.getElementById('submitBtn');
323
+ const progressWrap = document.getElementById('progressWrap');
324
+ const progressBar = document.getElementById('progressBar');
325
+ const progressLbl = document.getElementById('progressLabel');
326
+ const result = document.getElementById('result');
327
+
328
+ form.addEventListener('submit', async e => {
329
+ e.preventDefault();
330
+
331
+ // Reset
332
+ result.className = 'result';
333
+ result.innerHTML = '';
334
+ progressWrap.classList.add('visible');
335
+ progressBar.style.width = '10%';
336
+ progressLbl.textContent = 'Envoi du fichier…';
337
+ submitBtn.disabled = true;
338
+
339
+ // Animate progress (fake)
340
+ let pct = 10;
341
+ const ticker = setInterval(() => {
342
+ if (pct < 85) { pct += 3; progressBar.style.width = pct + '%'; }
343
+ }, 600);
344
+
345
+ progressLbl.textContent = 'Analyse IA en cours…';
346
+
347
+ try {
348
+ const fd = new FormData(form);
349
+ const resp = await fetch('/extract', { method: 'POST', body: fd });
350
+
351
+ clearInterval(ticker);
352
+ progressBar.style.width = '100%';
353
+
354
+ if (!resp.ok) {
355
+ const err = await resp.json();
356
+ throw new Error(err.detail || 'Erreur serveur');
357
+ }
358
+
359
+ const count = resp.headers.get('X-Article-Count') || '?';
360
+ const blob = await resp.blob();
361
+ const url = URL.createObjectURL(blob);
362
+
363
+ progressWrap.classList.remove('visible');
364
+ result.className = 'result success';
365
+ result.innerHTML = `
366
+ <div class="result-text"><strong>${count}</strong> articles extraits</div>
367
+ <a class="download-btn" href="${url}" download="articles.csv">Télécharger CSV</a>
368
+ `;
369
+ } catch (err) {
370
+ clearInterval(ticker);
371
+ progressWrap.classList.remove('visible');
372
+ result.className = 'result error';
373
+ result.textContent = err.message;
374
+ } finally {
375
+ submitBtn.disabled = false;
376
+ }
377
+ });
378
+ </script>
379
+ </body>
380
+ </html>