Spaces:
Running
Running
Create cleaning.py
Browse files- cleaning.py +123 -0
cleaning.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
import argparse
|
| 3 |
+
import re
|
| 4 |
+
import pdfplumber
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
def clean_text_for_rag(text: str) -> str:
|
| 8 |
+
"""
|
| 9 |
+
Nettoie le texte pour RAG : normalise les caractères spéciaux,
|
| 10 |
+
puis garde uniquement lettres (accents), chiffres, espaces et ponctuation simple.
|
| 11 |
+
"""
|
| 12 |
+
# Normalisation des caractères spéciaux
|
| 13 |
+
text = re.sub(
|
| 14 |
+
r"[’‘“”«»–—\u00A0\u202F…œŒæÆ©®™§°±×÷]",
|
| 15 |
+
lambda m: {
|
| 16 |
+
"’": "'", "‘": "'", "“": '"', "”": '"', "«": '"', "»": '"',
|
| 17 |
+
"–": "-", "—": "-", "…": "...", "œ": "oe", "Œ": "OE", "æ": "ae", "Æ": "AE",
|
| 18 |
+
"©": "(c)", "®": "(R)", "™": "TM", "§": "§", "°": "°", "±": "+/-", "×": "x", "÷": "/"
|
| 19 |
+
}.get(m.group(0), m.group(0)),
|
| 20 |
+
text
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# Nettoyage strict : garder lettres, chiffres, espaces, ponctuation simple
|
| 24 |
+
text = re.sub(r'[^a-zA-ZÀ-ÿæ-œ0-9\s\.\,\:\;\!\?\-\_\'\"\\(\)\–\…]', '', text)
|
| 25 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 26 |
+
|
| 27 |
+
return text
|
| 28 |
+
|
| 29 |
+
def extract_and_clean_pdf(pdf_path, output_path, two_columns=False):
|
| 30 |
+
"""
|
| 31 |
+
Extrait le texte du PDF et le nettoie pour RAG.
|
| 32 |
+
"""
|
| 33 |
+
print(f"[+] Extraction du texte depuis : {pdf_path}")
|
| 34 |
+
|
| 35 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 36 |
+
all_text = []
|
| 37 |
+
for page in pdf.pages:
|
| 38 |
+
if two_columns:
|
| 39 |
+
left = page.crop((0, 0, page.width / 2, page.height))
|
| 40 |
+
right = page.crop((page.width / 2, 0, page.width, page.height))
|
| 41 |
+
text_left = left.extract_text() or ""
|
| 42 |
+
text_right = right.extract_text() or ""
|
| 43 |
+
text = f"{text_left}\n\n{text_right}"
|
| 44 |
+
else:
|
| 45 |
+
text = page.extract_text()
|
| 46 |
+
|
| 47 |
+
if text:
|
| 48 |
+
all_text.append(text)
|
| 49 |
+
|
| 50 |
+
# Concaténer tout le texte
|
| 51 |
+
full_text = ' '.join(all_text)
|
| 52 |
+
# Nettoyer pour RAG
|
| 53 |
+
cleaned_text = clean_text_for_rag(full_text)
|
| 54 |
+
|
| 55 |
+
# Sauvegarder
|
| 56 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 57 |
+
f.write(cleaned_text)
|
| 58 |
+
|
| 59 |
+
print(f"[+] Texte nettoyé sauvegardé dans : {output_path}")
|
| 60 |
+
|
| 61 |
+
def extract_text(file_path, output_path):
|
| 62 |
+
"""
|
| 63 |
+
Extrait le texte des autres formats de fichier et le nettoie.
|
| 64 |
+
"""
|
| 65 |
+
print(f"[+] Extraction du texte depuis : {file_path}")
|
| 66 |
+
try:
|
| 67 |
+
# Essayer d'abord avec UTF-8
|
| 68 |
+
try:
|
| 69 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 70 |
+
lines = f.readlines()
|
| 71 |
+
except UnicodeDecodeError:
|
| 72 |
+
# Si UTF-8 échoue, essayer avec Latin-1 (ISO-8859-1)
|
| 73 |
+
print("[!] Le fichier n'est pas en UTF-8, tentative avec Latin-1")
|
| 74 |
+
with open(file_path, 'r', encoding='latin-1') as f:
|
| 75 |
+
lines = f.readlines()
|
| 76 |
+
|
| 77 |
+
# Nettoyer chaque ligne
|
| 78 |
+
cleaned_lines = [clean_text_for_rag(line.strip()) for line in lines if line.strip()]
|
| 79 |
+
|
| 80 |
+
# Joindre avec sauts de ligne pour un bon format .md
|
| 81 |
+
cleaned_text = '\n'.join(cleaned_lines)
|
| 82 |
+
|
| 83 |
+
# Sauvegarder dans le fichier .md
|
| 84 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 85 |
+
f.write(cleaned_text)
|
| 86 |
+
|
| 87 |
+
print(f"[+] Texte nettoyé sauvegardé dans : {output_path}")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Erreur lors de l'ouverture du fichier {file_path} : {e}")
|
| 90 |
+
raise
|
| 91 |
+
|
| 92 |
+
def main():
|
| 93 |
+
parser = argparse.ArgumentParser(description='Extraire et nettoyer un fichier pour le RAG. Sortie toujours en .md.')
|
| 94 |
+
parser.add_argument('input_file', type=str, help='Chemin vers le fichier à traiter (PDF, TXT, MD, etc.).')
|
| 95 |
+
parser.add_argument('output_md', type=str, help='Chemin du fichier Markdown (.md) de sortie.')
|
| 96 |
+
parser.add_argument('--two-columns', action='store_true', help='Forcer la lecture en deux colonnes (PDF OCR).')
|
| 97 |
+
|
| 98 |
+
args = parser.parse_args()
|
| 99 |
+
|
| 100 |
+
input_path = args.input_file
|
| 101 |
+
output_path = args.output_md # On garde le nom original
|
| 102 |
+
|
| 103 |
+
# Vérifier que le fichier existe
|
| 104 |
+
if not os.path.exists(input_path):
|
| 105 |
+
print(f"Erreur : Le fichier {input_path} n'existe pas.")
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
# Détecter l'extension du fichier d'entrée
|
| 109 |
+
_, ext = os.path.splitext(input_path.lower())
|
| 110 |
+
|
| 111 |
+
# Vérifier et corriger l'extension de sortie si nécessaire
|
| 112 |
+
if not output_path.lower().endswith('.md'):
|
| 113 |
+
print("[!] Avertissement : Le fichier de sortie n'a pas l'extension .md. Il sera renommé en .md.")
|
| 114 |
+
output_path = os.path.splitext(output_path)[0] + '.md'
|
| 115 |
+
|
| 116 |
+
# Appeler la bonne fonction selon le format
|
| 117 |
+
if ext == '.pdf':
|
| 118 |
+
extract_and_clean_pdf(input_path, output_path, two_columns=args.two_columns)
|
| 119 |
+
else:
|
| 120 |
+
extract_text(input_path, output_path)
|
| 121 |
+
|
| 122 |
+
if __name__ == '__main__':
|
| 123 |
+
main()
|