Artemis-IA commited on
Commit
c45dd10
·
verified ·
1 Parent(s): 3935fbb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import yaml
4
+ import zipfile
5
+ import time
6
+ from pathlib import Path
7
+ from typing import List, Dict
8
+ import pandas as pd
9
+ import streamlit as st
10
+ from docling.document_converter import DocumentConverter, PdfFormatOption
11
+ from docling.datamodel.base_models import InputFormat
12
+ from docling.datamodel.document import ConversionStatus
13
+ from docling.datamodel.pipeline_options import (
14
+ PdfPipelineOptions,
15
+ AcceleratorOptions,
16
+ AcceleratorDevice,
17
+ TableStructureOptions,
18
+ TableFormerMode,
19
+ EasyOcrOptions,
20
+ TesseractCliOcrOptions,
21
+ TesseractOcrOptions,
22
+ RapidOcrOptions,
23
+ OcrMacOptions,
24
+ )
25
+ from loguru import logger
26
+
27
+ # Répertoires de sortie
28
+ OUTPUT_DIR = Path("output")
29
+ OUTPUT_DIR.mkdir(exist_ok=True)
30
+
31
+ FIGURES_DIR = OUTPUT_DIR / "figures"
32
+ FIGURES_DIR.mkdir(exist_ok=True)
33
+
34
+ TABLES_DIR = OUTPUT_DIR / "tables"
35
+ TABLES_DIR.mkdir(exist_ok=True)
36
+
37
+ # Fonction de création de DocumentConverter
38
+ def create_document_converter(
39
+ use_ocr: bool,
40
+ export_figures: bool,
41
+ export_tables: bool,
42
+ accelerator: str,
43
+ ocr_engine: str,
44
+ table_mode: str,
45
+ ocr_languages: List[str],
46
+ ) -> DocumentConverter:
47
+ accelerator_options = AcceleratorOptions(
48
+ num_threads=8,
49
+ device=AcceleratorDevice[accelerator.upper()],
50
+ )
51
+
52
+ table_structure_options = TableStructureOptions(
53
+ mode=table_mode,
54
+ do_cell_matching=True,
55
+ )
56
+
57
+ if ocr_engine == "easyocr":
58
+ ocr_options = EasyOcrOptions(lang=ocr_languages)
59
+ elif ocr_engine == "tesseract_cli":
60
+ ocr_options = TesseractCliOcrOptions(lang=ocr_languages)
61
+ elif ocr_engine == "tesserocr":
62
+ ocr_options = TesseractOcrOptions(lang=ocr_languages)
63
+ elif ocr_engine == "rapidocr":
64
+ ocr_options = RapidOcrOptions(lang=ocr_languages)
65
+ elif ocr_engine == "ocrmac":
66
+ ocr_options = OcrMacOptions(lang=ocr_languages)
67
+ else:
68
+ raise ValueError(f"Moteur OCR non pris en charge : {ocr_engine}")
69
+
70
+ pipeline_options = PdfPipelineOptions(
71
+ do_ocr=use_ocr,
72
+ generate_page_images=True,
73
+ generate_picture_images=export_figures,
74
+ generate_table_images=export_tables,
75
+ accelerator_options=accelerator_options,
76
+ table_structure_options=table_structure_options,
77
+ ocr_options=ocr_options,
78
+ )
79
+
80
+ return DocumentConverter(
81
+ allowed_formats=[
82
+ InputFormat.PDF,
83
+ InputFormat.DOCX,
84
+ InputFormat.PPTX,
85
+ InputFormat.HTML,
86
+ InputFormat.IMAGE,
87
+ ],
88
+ format_options={
89
+ InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options),
90
+ },
91
+ )
92
+
93
+ # Fonction pour créer un fichier ZIP
94
+ def create_zip_file(output_dir: Path, zip_name: str) -> str:
95
+ zip_path = output_dir / zip_name
96
+ with zipfile.ZipFile(zip_path, "w") as zipf:
97
+ for file_path in output_dir.rglob("*"):
98
+ if file_path.is_file():
99
+ zipf.write(file_path, arcname=file_path.relative_to(output_dir))
100
+ return str(zip_path)
101
+
102
+ # Fonction pour calculer les métriques (exemple : temps d'inférence, nombre de tables, figures, etc.)
103
+ def compute_metrics(conversion_results, start_time):
104
+ metrics = {
105
+ "total_documents": len(conversion_results),
106
+ "successful_conversions": sum(1 for res in conversion_results if res.status == ConversionStatus.SUCCESS),
107
+ "failed_conversions": sum(1 for res in conversion_results if res.status != ConversionStatus.SUCCESS),
108
+ "total_time": time.time() - start_time,
109
+ "tables_extracted": sum(len(res.document.tables) for res in conversion_results if res.status == ConversionStatus.SUCCESS),
110
+ "figures_extracted": sum(len(res.document.pictures) for res in conversion_results if res.status == ConversionStatus.SUCCESS),
111
+ }
112
+ return metrics
113
+
114
+ # Interface Streamlit
115
+ st.set_page_config(page_title="Docling Dynamic Processor", layout="wide")
116
+ st.title("Docling Dynamic Processor - Analyse et Extraction de Documents")
117
+
118
+ # Formulaire de configuration
119
+ st.sidebar.header("Options de configuration")
120
+ use_ocr = st.sidebar.checkbox("Activer l'OCR", value=True)
121
+ export_figures = st.sidebar.checkbox("Exporter les figures", value=True)
122
+ export_tables = st.sidebar.checkbox("Exporter les tableaux", value=True)
123
+ accelerator = st.sidebar.selectbox("Accélérateur", ["cpu", "cuda", "mps"], index=0)
124
+ ocr_engine = st.sidebar.selectbox("Moteur OCR", ["easyocr", "tesseract_cli", "tesserocr", "rapidocr", "ocrmac"])
125
+ table_mode = st.sidebar.selectbox("Mode Table", ["accurate", "fast"], index=0)
126
+ ocr_languages = st.sidebar.text_input("Langues OCR (ex: eng, fra)", value="eng").split(",")
127
+
128
+ # Zone de téléchargement
129
+ uploaded_files = st.file_uploader("Téléchargez vos fichiers (PDF, DOCX, etc.)", type=["pdf", "docx", "pptx"], accept_multiple_files=True)
130
+
131
+ if st.button("Lancer le traitement") and uploaded_files:
132
+ # Sauvegarder les fichiers téléchargés
133
+ input_paths = []
134
+ for uploaded_file in uploaded_files:
135
+ file_path = OUTPUT_DIR / uploaded_file.name
136
+ with open(file_path, "wb") as f:
137
+ f.write(uploaded_file.read())
138
+ input_paths.append(file_path)
139
+
140
+ # Démarrer le traitement
141
+ start_time = time.time()
142
+ converter = create_document_converter(
143
+ use_ocr,
144
+ export_figures,
145
+ export_tables,
146
+ accelerator,
147
+ ocr_engine,
148
+ table_mode,
149
+ ocr_languages,
150
+ )
151
+ conv_results = list(converter.convert_all(input_paths, raises_on_error=False))
152
+
153
+ # Traiter les fichiers et collecter les résultats
154
+ exported_files = {"figures": [], "tables": [], "exports": []}
155
+ for conv_res in conv_results:
156
+ if conv_res.status == ConversionStatus.SUCCESS:
157
+ doc_filename = conv_res.input.file.stem
158
+
159
+ # Export des tableaux
160
+ for table_ix, table in enumerate(conv_res.document.tables):
161
+ csv_file = OUTPUT_DIR / f"{doc_filename}-table-{table_ix+1}.csv"
162
+ table.export_to_dataframe().to_csv(csv_file, index=False)
163
+ exported_files["tables"].append(str(csv_file))
164
+
165
+ # Export des figures (sous forme d'images)
166
+ for fig_ix, figure in enumerate(conv_res.document.pictures):
167
+ fig_file = FIGURES_DIR / f"{doc_filename}-figure-{fig_ix+1}.png"
168
+ figure.image.save(fig_file)
169
+ exported_files["figures"].append(str(fig_file))
170
+
171
+ # Générer un ZIP contenant tous les fichiers
172
+ zip_file = create_zip_file(OUTPUT_DIR, "exported_results.zip")
173
+
174
+ # Calcul des métriques
175
+ metrics = compute_metrics(conv_results, start_time)
176
+
177
+ # Afficher les résultats
178
+ st.success("Traitement terminé!")
179
+ st.metric("Documents traités avec succès", metrics["successful_conversions"])
180
+ st.metric("Échecs", metrics["failed_conversions"])
181
+ st.metric("Temps total (s)", f"{metrics['total_time']:.2f}")
182
+ st.metric("Total des tableaux extraits", metrics["tables_extracted"])
183
+ st.metric("Total des figures extraites", metrics["figures_extracted"])
184
+
185
+ st.download_button(
186
+ label="Télécharger tous les résultats (ZIP)",
187
+ data=open(zip_file, "rb").read(),
188
+ file_name="exported_results.zip",
189
+ mime="application/zip",
190
+ )