Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python | |
| import argparse | |
| import re | |
| import pdfplumber | |
| import os | |
| def clean_text_for_rag(text: str) -> str: | |
| """ | |
| Nettoie le texte pour RAG : normalise les caractères spéciaux, | |
| puis garde uniquement lettres (accents), chiffres, espaces et ponctuation simple. | |
| """ | |
| # Normalisation des caractères spéciaux | |
| text = re.sub( | |
| r"[’‘“”«»–—\u00A0\u202F…œŒæÆ©®™§°±×÷]", | |
| lambda m: { | |
| "’": "'", "‘": "'", "“": '"', "”": '"', "«": '"', "»": '"', | |
| "–": "-", "—": "-", "…": "...", "œ": "oe", "Œ": "OE", "æ": "ae", "Æ": "AE", | |
| "©": "(c)", "®": "(R)", "™": "TM", "§": "§", "°": "°", "±": "+/-", "×": "x", "÷": "/" | |
| }.get(m.group(0), m.group(0)), | |
| text | |
| ) | |
| # Nettoyage strict : garder lettres, chiffres, espaces, ponctuation simple | |
| text = re.sub(r'[^a-zA-ZÀ-ÿæ-œ0-9\s\.\,\:\;\!\?\-\_\'\"\\(\)\–\…]', '', text) | |
| text = re.sub(r'\s+', ' ', text).strip() | |
| return text | |
| def extract_and_clean_pdf(pdf_path, output_path): | |
| """ | |
| Extrait le texte du PDF et le nettoie pour RAG. | |
| """ | |
| print(f"[+] Extraction du texte depuis : {pdf_path}") | |
| with pdfplumber.open(pdf_path) as pdf: | |
| all_text = [] | |
| for page in pdf.pages: | |
| text = page.extract_text() | |
| if text: | |
| all_text.append(text) | |
| # Concaténer tout le texte | |
| full_text = ' '.join(all_text) | |
| # Nettoyer pour RAG | |
| cleaned_text = clean_text_for_rag(full_text) | |
| # Sauvegarder | |
| with open(output_path, 'w', encoding='utf-8') as f: | |
| f.write(cleaned_text) | |
| print(f"[+] Texte nettoyé sauvegardé dans : {output_path}") | |
| def extract_text(file_path, output_path): | |
| """ | |
| Extrait le texte des autres formats de fichier et le nettoie. | |
| """ | |
| print(f"[+] Extraction du texte depuis : {file_path}") | |
| try: | |
| with open(file_path, 'r', encoding='utf-8') as f: | |
| lines = f.readlines() | |
| # Nettoyer chaque ligne | |
| cleaned_lines = [clean_text_for_rag(line.strip()) for line in lines if line.strip()] | |
| # Joindre avec sauts de ligne pour un bon format .md | |
| cleaned_text = '\n'.join(cleaned_lines) | |
| # Sauvegarder dans le fichier .md | |
| with open(output_path, 'w', encoding='utf-8') as f: | |
| f.write(cleaned_text) | |
| print(f"[+] Texte nettoyé sauvegardé dans : {output_path}") | |
| except Exception as e: | |
| print(f"Erreur lors de l'ouverture du fichier {file_path} : {e}") | |
| raise | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Extraire et nettoyer un fichier pour le RAG. Sortie toujours en .md.') | |
| parser.add_argument('input_file', type=str, help='Chemin vers le fichier à traiter (PDF, TXT, MD, etc.).') | |
| parser.add_argument('output_md', type=str, help='Chemin du fichier Markdown (.md) de sortie.') | |
| args = parser.parse_args() | |
| input_path = args.input_file | |
| output_path = args.output_md # On garde le nom original | |
| # Vérifier que le fichier existe | |
| if not os.path.exists(input_path): | |
| print(f"Erreur : Le fichier {input_path} n'existe pas.") | |
| return | |
| # Détecter l'extension du fichier d'entrée | |
| _, ext = os.path.splitext(input_path.lower()) | |
| # Vérifier et corriger l'extension de sortie si nécessaire | |
| if not output_path.lower().endswith('.md'): | |
| print(f"[!] Avertissement : Le fichier de sortie n'a pas l'extension .md. Il sera renommé en .md.") | |
| output_path = os.path.splitext(output_path)[0] + '.md' | |
| # Appeler la bonne fonction selon le format | |
| if ext == '.pdf': | |
| extract_and_clean_pdf(input_path, output_path) | |
| else: | |
| extract_text(input_path, output_path) | |
| if __name__ == '__main__': | |
| main() |