lsottani commited on
Commit
f71d7f0
·
verified ·
1 Parent(s): e871e70

Upload file_cleaning_ui.py

Browse files
Files changed (1) hide show
  1. file_cleaning_ui.py +142 -0
file_cleaning_ui.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import re
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ import pdfplumber
9
+ import docx
10
+ import gradio as gr
11
+
12
+ def clean_text_for_rag(text: str) -> str:
13
+ """Normalise et nettoie le texte pour un usage RAG."""
14
+ # Normalisation des caractères typographiques
15
+ text = re.sub(
16
+ r"[’‘“”«»–—\u00A0\u202F…œŒæÆ©®™§°±×÷]",
17
+ lambda m: {
18
+ "’": "'", "‘": "'", "“": '"', "”": '"',
19
+ "«": '"', "»": '"', "–": "-", "—": "-",
20
+ "…": "...", "œ": "oe", "Œ": "OE",
21
+ "æ": "ae", "Æ": "AE", "©": "(c)", "®": "(R)",
22
+ "™": "TM", "§": "§", "°": "°", "±": "+/-",
23
+ "×": "x", "÷": "/"
24
+ }.get(m.group(0), m.group(0)),
25
+ text,
26
+ )
27
+ # Conserver uniquement les caractères suivants
28
+ text = re.sub(r'[^a-zA-ZÀ-ÿæ-œ0-9\s\.\,\:\;\!\?\-\_\'\"\\\(\)]', '', text)
29
+ # Réduire les espaces multiples
30
+ return re.sub(r'\s+', ' ', text).strip()
31
+
32
+
33
+ def extract_and_clean_pdf(pdf_path: str) -> str:
34
+ """Ouvre le PDF, récupère le texte et le nettoie."""
35
+ print(f"[+] Extraction du PDF : {pdf_path}")
36
+ all_pages = []
37
+ with pdfplumber.open(pdf_path) as pdf:
38
+ for page in pdf.pages:
39
+ txt = page.extract_text()
40
+ if txt:
41
+ all_pages.append(txt)
42
+ return clean_text_for_rag(" ".join(all_pages))
43
+
44
+
45
+ def extract_and_clean_docx(docx_path: str) -> str:
46
+ """Lit un fichier DOCX et le nettoie."""
47
+ print(f"[+] Extraction du DOCX : {docx_path}")
48
+ doc = docx.Document(docx_path)
49
+ paragraphs = []
50
+ for para in doc.paragraphs:
51
+ text = para.text.strip()
52
+ if text:
53
+ paragraphs.append(text)
54
+ return clean_text_for_rag(" ".join(paragraphs))
55
+
56
+ def extract_and_clean_txt(txt_path: str) -> str:
57
+ """Lit un fichier texte (txt, md, …) et le nettoie."""
58
+ print(f"[+] Lecture du fichier texte : {txt_path}")
59
+ with open(txt_path, "r", encoding="utf-8") as f:
60
+ lines = f.readlines()
61
+ cleaned = [
62
+ clean_text_for_rag(line.strip())
63
+ for line in lines
64
+ if line.strip()
65
+ ]
66
+ return "\n".join(cleaned)
67
+
68
+ def process_file(input_file: gr.File, output_name: str) -> str:
69
+ """
70
+ - Detecte le type (PDF ou texte)
71
+ - Effectue l'extraction + nettoyage
72
+ - Crée un fichier temporaire **avec le nom choisi** (output_name)
73
+ - Retourne le chemin du fichier temporaire (Gradio le propose en téléchargement)
74
+ """
75
+ input_path = input_file.name
76
+ _, ext = os.path.splitext(input_path.lower())
77
+
78
+ if ext == ".pdf":
79
+ cleaned_text = extract_and_clean_pdf(input_path)
80
+ elif ext == ".docx":
81
+ cleaned_text = extract_and_clean_docx(input_path)
82
+ else:
83
+ cleaned_text = extract_and_clean_txt(input_path)
84
+
85
+ output_name = output_name.strip()
86
+ if not output_name.lower().endswith(".md"):
87
+ output_name = f"{output_name}.md"
88
+
89
+ temp_dir = tempfile.mkdtemp()
90
+ out_path = os.path.join(temp_dir, output_name)
91
+
92
+ with open(out_path, "w", encoding="utf-8") as f:
93
+ f.write(cleaned_text)
94
+
95
+ return out_path
96
+
97
+ with gr.Blocks(title="Nettoyage de texte pour RAG") as demo:
98
+ gr.Markdown("# 📄 Nettoyage d'un fichier pour utilisation RAG")
99
+ gr.Markdown(
100
+ "Déposez simplement votre fichier : nous nous chargeons d’extraire son contenu textuel, de le nettoyer "
101
+ "puis de vous le restituer en format markdown **sous le nom que vous choisissez.**"
102
+ )
103
+
104
+ with gr.Row():
105
+ with gr.Column(scale=1):
106
+ input_file = gr.File(
107
+ label="Déposez votre fichier ici",
108
+ file_types=["pdf", "txt", "md", "docx"],
109
+ )
110
+ output_name = gr.Textbox(
111
+ value="output.md",
112
+ label="Nom du fichier de sortie (en .md)",
113
+ placeholder="exemple.md",
114
+ interactive=True,
115
+ )
116
+ submit_btn = gr.Button("Traiter le fichier", variant="primary")
117
+ with gr.Column(scale=1):
118
+ output_file = gr.File(
119
+ label="Fichier nettoyé (.md)",
120
+ file_types=["md"],
121
+ )
122
+
123
+ submit_btn.click(
124
+ fn=process_file,
125
+ inputs=[input_file, output_name],
126
+ outputs=output_file,
127
+ )
128
+
129
+ gr.Markdown(
130
+ """
131
+ ---
132
+ **Prétraitements effectués :**
133
+ - Suppression des symboles non imprimables et des caractères parasites
134
+ - Conservation des lettres (y compris accentuées), chiffres, espaces et ponctuation simple
135
+ - Normalisation des espaces pour un texte harmonieux
136
+ - Export automatique au format **`.md`**
137
+
138
+ """
139
+ )
140
+
141
+ if __name__ == "__main__":
142
+ demo.launch(share=True)