Spaces:
Sleeping
Sleeping
File size: 21,184 Bytes
235d083 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | """
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__)
@dataclass
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) |