Spaces:
Sleeping
Sleeping
Download main.py from Datartiste/askpdf: direct link, hf CLI and curl.
- Browser
- Download file 21.2 kB
-
https://huggingface.co/spaces/Datartiste/askpdf/resolve/main/main.py
- Command line
-
hf download hf://spaces/Datartiste/askpdf/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Datartiste/askpdf/resolve/main/main.py
21.2 kB
| """ | |
| Pipeline PDF vers FAISS - Version Corrigée | |
| Traite un PDF pharmaceutique et crée un index de recherche sémantique | |
| """ | |
| import os | |
| import sys | |
| import re | |
| import numpy as np | |
| import faiss | |
| import pickle | |
| import time | |
| from typing import List, Tuple, Dict, Optional | |
| from pathlib import Path | |
| from dataclasses import dataclass | |
| import logging | |
| # Configuration du logging | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| class DocumentChunk: | |
| """Représente un chunk de document avec ses métadonnées""" | |
| text: str | |
| page_number: int | |
| chunk_index: int | |
| start_char: int | |
| end_char: int | |
| word_count: int = 0 | |
| source_file: str = "" # Ajout pour multi-fichiers | |
| def __post_init__(self): | |
| self.word_count = len(self.text.split()) | |
| class OptimalPDFVectorizer: | |
| """ | |
| Vectorizer PDF optimisé avec gestion d'erreurs robuste | |
| """ | |
| def __init__(self, | |
| model_name: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", | |
| chunk_size: int = 1000, | |
| chunk_overlap: int = 200, | |
| min_chunk_length: int = 50): | |
| """ | |
| Initialise le vectorizer avec un modèle multilingue optimisé | |
| """ | |
| self.model_name = model_name | |
| self.chunk_size = chunk_size | |
| self.chunk_overlap = chunk_overlap | |
| self.min_chunk_length = min_chunk_length | |
| # Initialisation différée des composants | |
| self.embedding_model = None | |
| self.embedding_dim = None | |
| self.index = None | |
| self.chunks = [] | |
| self._setup_directories() | |
| def _setup_directories(self): | |
| """Crée les dossiers nécessaires""" | |
| self.output_dir = Path("./faiss_index") | |
| self.output_dir.mkdir(exist_ok=True) | |
| def _initialize_model(self): | |
| """Initialise le modèle de manière différée avec gestion d'erreurs""" | |
| if self.embedding_model is None: | |
| try: | |
| logger.info(f"🤖 Chargement du modèle {self.model_name}...") | |
| # Vérifier si sentence-transformers est installé | |
| try: | |
| from sentence_transformers import SentenceTransformer | |
| except ImportError: | |
| raise ImportError( | |
| "sentence-transformers n'est pas installé. " | |
| "Installez-le avec: pip install sentence-transformers" | |
| ) | |
| self.embedding_model = SentenceTransformer(self.model_name) | |
| self.embedding_dim = self.embedding_model.get_sentence_embedding_dimension() | |
| logger.info(f"✅ Modèle chargé - Dimension: {self.embedding_dim}") | |
| except Exception as e: | |
| logger.error(f"❌ Erreur chargement modèle: {e}") | |
| logger.error("💡 Vérifiez votre connexion internet et les dépendances") | |
| raise | |
| def extract_text_from_pdf(self, pdf_path: str) -> List[Tuple[str, int]]: | |
| """ | |
| Extraction robuste du texte PDF avec plusieurs méthodes de fallback | |
| """ | |
| pdf_path = Path(pdf_path) | |
| if not pdf_path.exists(): | |
| raise FileNotFoundError(f"PDF non trouvé: {pdf_path}") | |
| logger.info(f"📄 Extraction du PDF: {pdf_path.name}") | |
| pages_text = [] | |
| # Vérifier si pdfplumber est installé | |
| try: | |
| import pdfplumber | |
| except ImportError: | |
| raise ImportError( | |
| "pdfplumber n'est pas installé. " | |
| "Installez-le avec: pip install pdfplumber" | |
| ) | |
| # Méthode principale : pdfplumber | |
| try: | |
| with pdfplumber.open(pdf_path) as pdf: | |
| total_pages = len(pdf.pages) | |
| logger.info(f"📖 {total_pages} pages détectées") | |
| for page_num, page in enumerate(pdf.pages, 1): | |
| try: | |
| # Extraction du texte | |
| text = page.extract_text() | |
| if text and text.strip(): | |
| # Nettoyage et validation | |
| cleaned_text = self._clean_text(text) | |
| if len(cleaned_text) > self.min_chunk_length: | |
| pages_text.append((cleaned_text, page_num)) | |
| logger.debug(f"Page {page_num}: {len(cleaned_text)} caractères") | |
| except Exception as e: | |
| logger.warning(f"⚠️ Erreur page {page_num}: {e}") | |
| continue | |
| except Exception as e: | |
| logger.error(f"❌ Erreur extraction PDF: {e}") | |
| raise | |
| if not pages_text: | |
| raise ValueError("Aucun texte extrait du PDF") | |
| logger.info(f"✅ {len(pages_text)} pages extraites avec succès") | |
| return pages_text | |
| def _clean_text(self, text: str) -> str: | |
| """ | |
| Nettoyage intelligent du texte | |
| """ | |
| if not text: | |
| return "" | |
| # Suppression des caractères de contrôle | |
| text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f]', '', text) | |
| # Normalisation des espaces et sauts de ligne | |
| text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text) # Max 2 sauts de ligne consécutifs | |
| text = re.sub(r'[ \t]+', ' ', text) # Espaces multiples | |
| text = re.sub(r' ?\n ?', '\n', text) # Espaces autour des sauts de ligne | |
| # Suppression des tirets de fin de ligne (césure) | |
| text = re.sub(r'-\n([a-z])', r'\1', text) | |
| return text.strip() | |
| def create_chunks(self, pages_text: List[Tuple[str, int]], source_file: str = "") -> List[DocumentChunk]: | |
| """ | |
| Création intelligente de chunks avec optimisation sémantique | |
| """ | |
| logger.info("🔧 Création des chunks...") | |
| chunks = [] | |
| chunk_index = 0 | |
| for page_text, page_num in pages_text: | |
| text_length = len(page_text) | |
| if text_length <= self.chunk_size: | |
| # Page entière si assez petite | |
| if text_length >= self.min_chunk_length: | |
| chunk = DocumentChunk( | |
| text=page_text, | |
| page_number=page_num, | |
| chunk_index=chunk_index, | |
| start_char=0, | |
| end_char=text_length, | |
| source_file=source_file | |
| ) | |
| chunks.append(chunk) | |
| chunk_index += 1 | |
| continue | |
| # Découpage intelligent pour pages longues | |
| start = 0 | |
| while start < text_length: | |
| end = min(start + self.chunk_size, text_length) | |
| if end < text_length: | |
| # Recherche du meilleur point de coupure | |
| best_cut = self._find_best_cut_point(page_text, start, end) | |
| if best_cut > start: | |
| end = best_cut | |
| chunk_text = page_text[start:end].strip() | |
| # Validation du chunk | |
| if len(chunk_text) >= self.min_chunk_length: | |
| chunk = DocumentChunk( | |
| text=chunk_text, | |
| page_number=page_num, | |
| chunk_index=chunk_index, | |
| start_char=start, | |
| end_char=end, | |
| source_file=source_file | |
| ) | |
| chunks.append(chunk) | |
| chunk_index += 1 | |
| # Calcul du prochain début avec chevauchement intelligent | |
| next_start = end - self.chunk_overlap | |
| # Éviter les chevauchements trop courts | |
| if next_start <= start + 50: | |
| next_start = end | |
| start = next_start | |
| logger.info(f"✅ {len(chunks)} chunks créés") | |
| # Statistiques | |
| if chunks: | |
| total_words = sum(chunk.word_count for chunk in chunks) | |
| avg_words = total_words / len(chunks) | |
| logger.info(f"📊 Moyenne: {avg_words:.1f} mots/chunk, Total: {total_words} mots") | |
| return chunks | |
| def _find_best_cut_point(self, text: str, start: int, end: int) -> int: | |
| """ | |
| Trouve le meilleur point de coupure pour préserver le sens | |
| """ | |
| search_window = 100 # Fenêtre de recherche autour du point de coupure | |
| search_start = max(start, end - search_window) | |
| search_end = min(len(text), end + search_window // 2) | |
| search_text = text[search_start:search_end] | |
| # Priorités de coupure (par ordre de préférence) | |
| cut_patterns = [ | |
| r'\n\n', # Double saut de ligne | |
| r'\. [A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]', # Fin de phrase + majuscule | |
| r'\?\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]', # Point d'interrogation + majuscule | |
| r'!\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]', # Point d'exclamation + majuscule | |
| r'\n', # Simple saut de ligne | |
| r'[;:]\s+', # Ponctuation forte | |
| r',\s+', # Virgule | |
| r'\s+' # Espace | |
| ] | |
| best_pos = end | |
| for pattern in cut_patterns: | |
| matches = list(re.finditer(pattern, search_text)) | |
| if matches: | |
| # Prendre la correspondance la plus proche du point de coupure original | |
| target_pos = end - search_start | |
| closest_match = min(matches, key=lambda m: abs(m.start() - target_pos)) | |
| candidate_pos = search_start + closest_match.end() | |
| # Vérifier que c'est dans une plage acceptable | |
| if start + 200 <= candidate_pos <= end + 50: | |
| best_pos = candidate_pos | |
| break | |
| return min(best_pos, len(text)) | |
| def create_embeddings(self, chunks: List[DocumentChunk]) -> np.ndarray: | |
| """ | |
| Création optimisée des embeddings avec gestion de batch | |
| """ | |
| self._initialize_model() | |
| logger.info(f"🧠 Création des embeddings pour {len(chunks)} chunks...") | |
| if not chunks: | |
| raise ValueError("Aucun chunk à traiter") | |
| texts = [chunk.text for chunk in chunks] | |
| try: | |
| # Traitement par batch pour optimiser la mémoire | |
| batch_size = 32 | |
| all_embeddings = [] | |
| for i in range(0, len(texts), batch_size): | |
| batch = texts[i:i + batch_size] | |
| logger.debug(f"Traitement batch {i//batch_size + 1}/{(len(texts)-1)//batch_size + 1}") | |
| batch_embeddings = self.embedding_model.encode( | |
| batch, | |
| convert_to_numpy=True, | |
| show_progress_bar=False, | |
| normalize_embeddings=True # Normalisation directe | |
| ) | |
| all_embeddings.append(batch_embeddings) | |
| # Concaténation des résultats | |
| embeddings = np.vstack(all_embeddings) | |
| logger.info(f"✅ Embeddings créés: {embeddings.shape}") | |
| return embeddings | |
| except Exception as e: | |
| logger.error(f"❌ Erreur création embeddings: {e}") | |
| raise | |
| def build_faiss_index(self, embeddings: np.ndarray) -> faiss.Index: | |
| """ | |
| Construction d'un index FAISS optimisé | |
| """ | |
| logger.info("🔍 Construction de l'index FAISS...") | |
| # Choix de l'index selon la taille des données | |
| n_vectors, dim = embeddings.shape | |
| if n_vectors < 1000: | |
| # Index exact pour petites collections | |
| index = faiss.IndexFlatIP(dim) | |
| logger.info("📋 Index exact (IndexFlatIP)") | |
| else: | |
| # Index approximatif pour collections plus importantes | |
| nlist = min(100, n_vectors // 10) # Nombre de clusters | |
| quantizer = faiss.IndexFlatIP(dim) | |
| index = faiss.IndexIVFFlat(quantizer, dim, nlist) | |
| # Entraînement de l'index | |
| logger.info(f"🏋️ Entraînement de l'index avec {nlist} clusters...") | |
| index.train(embeddings) | |
| logger.info("📋 Index approximatif (IndexIVFFlat)") | |
| # Ajout des vecteurs | |
| index.add(embeddings) | |
| logger.info(f"✅ Index construit avec {index.ntotal} vecteurs") | |
| return index | |
| def process_pdf(self, pdf_path: str, save_automatically: bool = True) -> Dict: | |
| """ | |
| Pipeline complète avec rapport détaillé | |
| """ | |
| start_time = time.time() | |
| logger.info(f"🚀 Début du traitement: {Path(pdf_path).name}") | |
| try: | |
| # 1. Extraction | |
| pages_text = self.extract_text_from_pdf(pdf_path) | |
| # 2. Création des chunks | |
| source_file = Path(pdf_path).name | |
| self.chunks = self.create_chunks(pages_text, source_file) | |
| # 3. Création des embeddings | |
| embeddings = self.create_embeddings(self.chunks) | |
| # 4. Construction de l'index | |
| self.index = self.build_faiss_index(embeddings) | |
| # 5. Sauvegarde automatique | |
| if save_automatically: | |
| self.save_index() | |
| # Rapport final | |
| processing_time = time.time() - start_time | |
| report = { | |
| 'success': True, | |
| 'pdf_path': str(pdf_path), | |
| 'pages_processed': len(pages_text), | |
| 'chunks_created': len(self.chunks), | |
| 'embedding_dimension': self.embedding_dim, | |
| 'processing_time': processing_time, | |
| 'avg_chunk_words': np.mean([chunk.word_count for chunk in self.chunks]) if self.chunks else 0, | |
| 'total_words': sum(chunk.word_count for chunk in self.chunks) | |
| } | |
| logger.info(f"🎉 Traitement terminé en {processing_time:.1f}s") | |
| logger.info(f"📊 {report['pages_processed']} pages → {report['chunks_created']} chunks → {report['total_words']} mots") | |
| return report | |
| except Exception as e: | |
| logger.error(f"❌ Erreur traitement: {e}") | |
| raise | |
| def search(self, | |
| query: str, | |
| top_k: int = 5, | |
| score_threshold: float = 0.1) -> List[Tuple[DocumentChunk, float]]: | |
| """ | |
| Recherche sémantique avancée | |
| """ | |
| if self.index is None: | |
| raise ValueError("Index non initialisé - lancez process_pdf() d'abord") | |
| if not query.strip(): | |
| return [] | |
| self._initialize_model() | |
| logger.debug(f"🔍 Recherche: '{query[:50]}...'") | |
| try: | |
| # Embedding de la requête | |
| query_embedding = self.embedding_model.encode( | |
| [query], | |
| convert_to_numpy=True, | |
| normalize_embeddings=True | |
| ) | |
| # Recherche dans l'index | |
| search_k = min(top_k * 2, len(self.chunks), self.index.ntotal) | |
| scores, indices = self.index.search(query_embedding, search_k) | |
| # Filtrage et classement des résultats | |
| results = [] | |
| for score, idx in zip(scores[0], indices[0]): | |
| if idx >= 0 and idx < len(self.chunks) and score >= score_threshold: | |
| results.append((self.chunks[idx], float(score))) | |
| # Limitation au top_k final | |
| results = results[:top_k] | |
| logger.debug(f"✅ {len(results)} résultats trouvés") | |
| return results | |
| except Exception as e: | |
| logger.error(f"❌ Erreur recherche: {e}") | |
| return [] | |
| def save_index(self, save_dir: Optional[str] = None) -> Path: | |
| """ | |
| Sauvegarde complète avec métadonnées enrichies | |
| """ | |
| if self.index is None: | |
| raise ValueError("Aucun index à sauvegarder") | |
| save_path = Path(save_dir) if save_dir else self.output_dir | |
| save_path.mkdir(exist_ok=True) | |
| logger.info(f"💾 Sauvegarde dans: {save_path}") | |
| # Sauvegarde de l'index FAISS | |
| index_file = save_path / "faiss_index.bin" | |
| faiss.write_index(self.index, str(index_file)) | |
| # Métadonnées complètes | |
| metadata = { | |
| 'chunks': self.chunks, | |
| 'model_name': self.model_name, | |
| 'embedding_dim': self.embedding_dim, | |
| 'chunk_size': self.chunk_size, | |
| 'chunk_overlap': self.chunk_overlap, | |
| 'min_chunk_length': self.min_chunk_length, | |
| 'total_chunks': len(self.chunks), | |
| 'creation_time': time.time(), | |
| 'version': '1.0' | |
| } | |
| metadata_file = save_path / "metadata.pkl" | |
| with open(metadata_file, 'wb') as f: | |
| pickle.dump(metadata, f) | |
| # Sauvegarde des statistiques | |
| if self.chunks: | |
| stats = { | |
| 'pages': len(set(chunk.page_number for chunk in self.chunks)), | |
| 'total_words': sum(chunk.word_count for chunk in self.chunks), | |
| 'avg_words_per_chunk': np.mean([chunk.word_count for chunk in self.chunks]), | |
| 'chunk_lengths': [len(chunk.text) for chunk in self.chunks] | |
| } | |
| else: | |
| stats = {'pages': 0, 'total_words': 0, 'avg_words_per_chunk': 0, 'chunk_lengths': []} | |
| stats_file = save_path / "statistics.pkl" | |
| with open(stats_file, 'wb') as f: | |
| pickle.dump(stats, f) | |
| logger.info(f"✅ Sauvegarde terminée: {len(list(save_path.glob('*')))} fichiers") | |
| return save_path | |
| def load_index(self, save_dir: str) -> Dict: | |
| """ | |
| Chargement avec validation | |
| """ | |
| save_path = Path(save_dir) | |
| if not save_path.exists(): | |
| raise FileNotFoundError(f"Dossier introuvable: {save_path}") | |
| logger.info(f"📂 Chargement depuis: {save_path}") | |
| # Chargement de l'index | |
| index_file = save_path / "faiss_index.bin" | |
| if not index_file.exists(): | |
| raise FileNotFoundError(f"Index FAISS manquant: {index_file}") | |
| self.index = faiss.read_index(str(index_file)) | |
| # Chargement des métadonnées | |
| metadata_file = save_path / "metadata.pkl" | |
| if not metadata_file.exists(): | |
| raise FileNotFoundError(f"Métadonnées manquantes: {metadata_file}") | |
| with open(metadata_file, 'rb') as f: | |
| metadata = pickle.load(f) | |
| # Restauration des attributs | |
| self.chunks = metadata['chunks'] | |
| self.model_name = metadata['model_name'] | |
| self.embedding_dim = metadata['embedding_dim'] | |
| self.chunk_size = metadata['chunk_size'] | |
| self.chunk_overlap = metadata['chunk_overlap'] | |
| self.min_chunk_length = metadata.get('min_chunk_length', 50) | |
| logger.info(f"✅ Index chargé: {len(self.chunks)} chunks, dim={self.embedding_dim}") | |
| return { | |
| 'chunks_loaded': len(self.chunks), | |
| 'model_name': self.model_name, | |
| 'embedding_dim': self.embedding_dim, | |
| 'creation_time': metadata.get('creation_time', 'Unknown') | |
| } | |
| def test_vectorizer(): | |
| """ | |
| Test simple pour vérifier que tout fonctionne | |
| """ | |
| print("🚀 === TEST VECTORIZER ===\n") | |
| try: | |
| # Initialisation | |
| vectorizer = OptimalPDFVectorizer( | |
| chunk_size=500, | |
| chunk_overlap=100, | |
| min_chunk_length=50 | |
| ) | |
| print("✅ Vectorizer initialisé") | |
| print("✅ Test réussi - Le code fonctionne correctement") | |
| return True | |
| except Exception as e: | |
| print(f"❌ Erreur test: {e}") | |
| return False | |
| if __name__ == "__main__": | |
| # Exécuter le test simple | |
| success = test_vectorizer() | |
| if success: | |
| print("\n💡 Pour utiliser avec des PDFs, appelez process_pdf() avec le chemin de votre fichier") | |
| sys.exit(0 if success else 1) |