File size: 33,552 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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
"""
Pipeline PDF vers FAISS - Version OCR AMÉLIORÉE
Meilleure gestion des PDFs scannés + diagnostic automatique
MODÈLE CROSS-LINGUAL pour recherche FR→EN
"""

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

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

@dataclass
class DocumentChunk:
    text: str
    page_number: int
    chunk_index: int
    start_char: int
    end_char: int
    word_count: int = 0
    source_file: str = ""
    
    def __post_init__(self):
        self.word_count = len(self.text.split())

class OptimalPDFVectorizer:
    """Vectorizer PDF avec OCR robuste pour PDFs scannés"""
    
    def __init__(self, 
                 model_name: str = "intfloat/multilingual-e5-base",  # ✅ MODÈLE CROSS-LINGUAL
                 chunk_size: int = 1000,
                 chunk_overlap: int = 200,
                 min_chunk_length: int = 50,
                 use_ocr: bool = True,
                 ocr_language: str = 'fra',
                 ocr_dpi: int = 300,
                 ocr_preprocessing: bool = True,
                 auto_detect_scanned: bool = True):
        """
        Args:
            model_name: Modèle d'embeddings (multilingual-e5-base recommandé pour cross-lingual)
            use_ocr: Active l'OCR pour les PDFs scannés
            ocr_language: 'fra' pour français, 'eng' pour anglais, 'fra+eng' pour les deux
            ocr_dpi: Résolution pour conversion PDF en image (200-400 recommandé)
            ocr_preprocessing: Active le prétraitement des images pour améliorer l'OCR
            auto_detect_scanned: Détection automatique des PDFs scannés (mettre False pour forcer extraction normale)
        """
        self.model_name = model_name
        self.chunk_size = chunk_size
        self.chunk_overlap = chunk_overlap
        self.min_chunk_length = min_chunk_length
        self.use_ocr = use_ocr
        self.ocr_language = ocr_language
        self.ocr_dpi = ocr_dpi
        self.ocr_preprocessing = ocr_preprocessing
        self.auto_detect_scanned = auto_detect_scanned
        
        self.ocr_available = False
        
        self.embedding_model = None
        self.embedding_dim = None
        self.index = None
        self.chunks = []
        
        # Éviter le warning tokenizers avec fork
        os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
        
        self._setup_directories()
        self._check_ocr_availability()
        
    def _setup_directories(self):
        import tempfile
        self.output_dir = Path(tempfile.gettempdir()) / "faiss_index"
        self.output_dir.mkdir(exist_ok=True, parents=True)
    
    def _check_ocr_availability(self):
        """Vérifie si OCR est disponible et diagnostique les problèmes"""
        self.ocr_available = False
        
        if not self.use_ocr:
            logger.info("OCR désactivé (use_ocr=False)")
            return
        
        try:
            missing = []
            
            try:
                import pytesseract
            except ImportError:
                missing.append("pytesseract (pip install pytesseract)")
            
            try:
                from pdf2image import convert_from_path
            except ImportError:
                missing.append("pdf2image (pip install pdf2image)")
            
            try:
                from PIL import Image, ImageEnhance, ImageFilter
            except ImportError:
                missing.append("Pillow (pip install Pillow)")
            
            if missing:
                logger.error(f"❌ Dépendances OCR manquantes: {', '.join(missing)}")
                return
            
            try:
                import subprocess
                result = subprocess.run(['tesseract', '--version'], 
                                      capture_output=True, text=True, timeout=5)
                if result.returncode != 0:
                    logger.error("❌ Tesseract installé mais ne fonctionne pas correctement")
                    return
                
                langs_result = subprocess.run(['tesseract', '--list-langs'],
                                            capture_output=True, text=True, timeout=5)
                available_langs = langs_result.stdout.lower()
                
                required_langs = self.ocr_language.lower().split('+')
                missing_langs = [lang for lang in required_langs if lang not in available_langs]
                
                if missing_langs:
                    logger.warning(f"⚠️ Langues OCR manquantes: {missing_langs}")
                    logger.warning("Installation: brew install tesseract-lang (Mac) ou sudo apt install tesseract-ocr-fra (Linux)")
                
                self.ocr_available = True
                logger.info(f"✅ OCR Tesseract disponible (langue: {self.ocr_language})")
                
            except FileNotFoundError:
                logger.error("❌ Tesseract NON installé")
                logger.error("Installation:")
                logger.error("  - Mac: brew install tesseract tesseract-lang poppler")
                logger.error("  - Linux: sudo apt install tesseract-ocr tesseract-ocr-fra poppler-utils")
            except subprocess.TimeoutExpired:
                logger.error("❌ Timeout lors de la vérification de Tesseract")
            except Exception as e:
                logger.error(f"❌ Erreur vérification Tesseract: {e}")
        
        except Exception as e:
            logger.error(f"❌ Erreur inattendue lors de la vérification OCR: {e}")
            self.ocr_available = False
        
    def _initialize_model(self):
        if self.embedding_model is None:
            try:
                logger.info(f"Chargement du modèle {self.model_name}...")
                from sentence_transformers import SentenceTransformer
                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}")
                logger.info(f"✅ Recherche cross-linguale activée (FR↔EN supporté)")
            except Exception as e:
                logger.error(f"Erreur chargement modèle: {e}")
                raise
    
    def _is_scanned_pdf(self, pages_text: List[Tuple[str, int]], total_pages: int) -> bool:
        """Détection améliorée des PDFs scannés avec critères plus intelligents"""
        if not pages_text:
            logger.info("📊 Diagnostic: Aucune page extraite → PDF scanné")
            return True
        
        pages_with_content = 0
        total_chars = 0
        total_words = 0
        chars_on_content_pages = 0
        
        for text, _ in pages_text:
            text_clean = text.strip()
            if len(text_clean) > 100:
                pages_with_content += 1
                chars_this_page = len(text_clean)
                total_chars += chars_this_page
                chars_on_content_pages += chars_this_page
                total_words += len(text_clean.split())
        
        # Calculs
        extraction_rate = (pages_with_content / total_pages) * 100 if total_pages > 0 else 0
        avg_chars_per_page = total_chars / total_pages if total_pages > 0 else 0
        avg_words_per_page = total_words / total_pages if total_pages > 0 else 0
        
        # Nouveau : caractères moyens sur les pages qui ONT du contenu
        avg_chars_per_content_page = chars_on_content_pages / pages_with_content if pages_with_content > 0 else 0
        
        # Logging détaillé
        logger.info("📊 Diagnostic PDF:")
        logger.info(f"   - Pages avec contenu: {pages_with_content}/{total_pages} ({extraction_rate:.1f}%)")
        logger.info(f"   - Caractères moyens/page (toutes): {avg_chars_per_page:.0f}")
        logger.info(f"   - Caractères moyens/page (avec contenu): {avg_chars_per_content_page:.0f}")
        logger.info(f"   - Mots moyens/page: {avg_words_per_page:.0f}")
        
        # Critères améliorés pour détecter un PDF scanné
        # Un PDF est considéré comme scanné SI :
        # 1. Moins de 20% des pages ont du contenu (vraiment très peu)
        # OU
        # 2. Moins de 50% des pages ont du contenu ET les pages avec contenu ont <800 caractères en moyenne
        # OU  
        # 3. Toutes les pages ont du contenu mais <300 caractères en moyenne (OCR raté)
        
        very_low_extraction = extraction_rate < 20
        low_extraction_and_poor_content = (extraction_rate < 50 and avg_chars_per_content_page < 800)
        all_pages_but_poor = (extraction_rate > 90 and avg_chars_per_page < 300)
        
        is_scanned = very_low_extraction or low_extraction_and_poor_content or all_pages_but_poor
        
        if is_scanned:
            logger.warning(f"🔍 DÉTECTION: PDF scanné")
            if very_low_extraction:
                logger.warning(f"   → Raison: Très peu de pages avec contenu ({extraction_rate:.1f}%)")
            elif low_extraction_and_poor_content:
                logger.warning(f"   → Raison: Peu de pages ({extraction_rate:.1f}%) ET peu de contenu par page ({avg_chars_per_content_page:.0f} chars)")
            elif all_pages_but_poor:
                logger.warning(f"   → Raison: Toutes les pages mais contenu très pauvre ({avg_chars_per_page:.0f} chars/page)")
        else:
            logger.info(f"✅ DÉTECTION: PDF normal")
            if extraction_rate < 60:
                logger.info(f"   → Extraction partielle OK: les pages avec contenu sont riches ({avg_chars_per_content_page:.0f} chars/page)")
        
        return is_scanned
    
    def _preprocess_image_for_ocr(self, image):
        """Prétraitement avancé de l'image pour améliorer l'OCR"""
        from PIL import Image, ImageEnhance, ImageFilter
        
        if not self.ocr_preprocessing:
            return image
        
        try:
            if image.mode != 'L':
                image = image.convert('L')
            
            image = image.filter(ImageFilter.SHARPEN)
            
            enhancer = ImageEnhance.Contrast(image)
            image = enhancer.enhance(2.0)
            
            enhancer = ImageEnhance.Brightness(image)
            image = enhancer.enhance(1.2)
            
            threshold = 128
            image = image.point(lambda x: 0 if x < threshold else 255, '1')
            image = image.convert('L')
            
            return image
            
        except Exception as e:
            logger.warning(f"Erreur prétraitement image: {e}")
            return image
    
    def _extract_with_ocr(self, pdf_path: str, max_pages: Optional[int] = None) -> List[Tuple[str, int]]:
        """Extraction OCR améliorée avec prétraitement d'image
        
        Args:
            pdf_path: Chemin vers le PDF
            max_pages: Nombre maximum de pages à traiter (None = toutes les pages)
        """
        if not self.ocr_available:
            raise RuntimeError("OCR non disponible - vérifiez l'installation de Tesseract")
        
        try:
            import pytesseract
            from pdf2image import convert_from_path
            from PIL import Image
        except ImportError as e:
            raise ImportError(f"Installez les dépendances OCR: pip install pytesseract pdf2image Pillow")
        
        logger.info(f"🔍 Démarrage OCR Tesseract (DPI: {self.ocr_dpi}, Langue: {self.ocr_language})")
        
        try:
            logger.info("📸 Conversion PDF en images...")
            
            # Convertir seulement le nombre de pages demandé
            images = convert_from_path(
                pdf_path, 
                dpi=self.ocr_dpi,
                thread_count=4,
                fmt='png',
                last_page=max_pages if max_pages else None  # Limite à max_pages
            )
            
            total_pages = len(images)
            logger.info(f"📄 {total_pages} pages à traiter par OCR")
            
            pages_text = []
            successful_pages = 0
            
            for page_num, image in enumerate(images, 1):
                try:
                    processed_image = self._preprocess_image_for_ocr(image)
                    
                    custom_config = r'--oem 3 --psm 6'
                    
                    text = pytesseract.image_to_string(
                        processed_image,
                        lang=self.ocr_language,
                        config=custom_config
                    )
                    
                    if text and text.strip():
                        cleaned_text = self._clean_text(text)
                        
                        if len(cleaned_text) > self.min_chunk_length:
                            pages_text.append((cleaned_text, page_num))
                            successful_pages += 1
                            logger.info(f"✅ Page {page_num}/{total_pages} OK ({len(cleaned_text)} chars)")
                        else:
                            logger.warning(f"⚠️ Page {page_num}/{total_pages} - Texte trop court ({len(cleaned_text)} chars)")
                    else:
                        logger.warning(f"⚠️ Page {page_num}/{total_pages} - Aucun texte détecté")
                
                except Exception as e:
                    logger.error(f"❌ Erreur page {page_num}: {e}")
                    continue
            
            if not pages_text:
                raise ValueError(f"❌ Aucun texte extrait par OCR sur {total_pages} pages")
            
            success_rate = (successful_pages / total_pages) * 100
            logger.info(f"✅ OCR terminé: {successful_pages}/{total_pages} pages extraites ({success_rate:.1f}%)")
            
            if success_rate < 50:
                logger.warning("⚠️ Taux de réussite OCR faible (<50%). Vérifiez la qualité du PDF scanné.")
            
            return pages_text
            
        except Exception as e:
            logger.error(f"❌ Erreur OCR: {e}")
            raise
    
    def get_pdf_page_count(self, pdf_path: str) -> int:
        """Compte rapidement le nombre de pages d'un PDF sans l'extraire"""
        try:
            import pdfplumber
            with pdfplumber.open(pdf_path) as pdf:
                return len(pdf.pages)
        except Exception as e:
            logger.error(f"Erreur comptage pages: {e}")
            return 0
    
    def estimate_processing_time(self, pdf_path: str, max_pages: Optional[int] = None) -> Dict:
        """Estime le temps de traitement d'un PDF
        
        Returns:
            Dict avec 'total_pages', 'pages_to_process', 'estimated_time_seconds', 'estimated_time_formatted'
        """
        total_pages = self.get_pdf_page_count(pdf_path)
        
        if total_pages == 0:
            return {
                'total_pages': 0,
                'pages_to_process': 0,
                'estimated_time_seconds': 0,
                'estimated_time_formatted': "Impossible d'estimer"
            }
        
        pages_to_process = min(max_pages, total_pages) if max_pages else total_pages
        
        # Temps estimés (en secondes par page)
        # Ces valeurs sont approximatives et peuvent varier selon la machine
        time_per_page_normal = 0.7  # Extraction pdfplumber
        time_per_page_ocr = 3.5     # OCR Tesseract
        time_per_chunk_embedding = 0.02  # Création des embeddings
        
        # Estimation du nombre de chunks (approximatif: ~2-3 chunks par page)
        estimated_chunks = pages_to_process * 2.5
        
        # On ne sait pas encore si c'est un PDF scanné, donc on estime pour le cas normal
        # et on indique que ça peut être plus long si OCR
        extraction_time = pages_to_process * time_per_page_normal
        embedding_time = estimated_chunks * time_per_chunk_embedding
        index_time = 2  # Temps de construction de l'index FAISS
        
        total_time_normal = extraction_time + embedding_time + index_time
        total_time_ocr = (pages_to_process * time_per_page_ocr) + embedding_time + index_time
        
        # Formater le temps
        def format_time(seconds):
            if seconds < 60:
                return f"{int(seconds)}s"
            elif seconds < 3600:
                minutes = int(seconds // 60)
                secs = int(seconds % 60)
                return f"{minutes}min {secs}s"
            else:
                hours = int(seconds // 3600)
                minutes = int((seconds % 3600) // 60)
                return f"{hours}h {minutes}min"
        
        return {
            'total_pages': total_pages,
            'pages_to_process': pages_to_process,
            'estimated_time_normal': total_time_normal,
            'estimated_time_ocr': total_time_ocr,
            'estimated_time_formatted_normal': format_time(total_time_normal),
            'estimated_time_formatted_ocr': format_time(total_time_ocr),
            'estimated_chunks': int(estimated_chunks)
        }
    
    def extract_text_from_pdf(self, pdf_path: str, force_ocr: bool = False, max_pages: Optional[int] = None) -> List[Tuple[str, int]]:
        """Extraction avec fallback OCR automatique + diagnostics
        
        Args:
            pdf_path: Chemin vers le PDF
            force_ocr: Force l'utilisation de l'OCR
            max_pages: Nombre maximum de pages à traiter (None = toutes les pages)
        """
        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}")
        if max_pages:
            logger.info(f"⚠️ Limitation: {max_pages} premières pages seulement")
        
        # Si OCR forcé
        if force_ocr:
            logger.info("🔧 Mode OCR forcé activé")
            if self.ocr_available:
                return self._extract_with_ocr(str(pdf_path), max_pages)
            else:
                raise RuntimeError("OCR forcé mais non disponible")
        
        try:
            import pdfplumber
        except ImportError:
            raise ImportError("pip install pdfplumber")
        
        pages_text = []
        total_pages = 0
        
        # Tentative d'extraction normale
        try:
            logger.info("🔄 Extraction normale avec pdfplumber...")
            with pdfplumber.open(pdf_path) as pdf:
                total_pages = len(pdf.pages)
                
                # Limiter le nombre de pages si max_pages est défini
                pages_to_process = min(max_pages, total_pages) if max_pages else total_pages
                
                logger.info(f"📄 {total_pages} pages détectées - Traitement de {pages_to_process} pages")
                
                for page_num, page in enumerate(pdf.pages[:pages_to_process], 1):
                    try:
                        text = page.extract_text()
                        
                        if text and text.strip():
                            cleaned_text = self._clean_text(text)
                            
                            if len(cleaned_text) > self.min_chunk_length:
                                pages_text.append((cleaned_text, page_num))
                    
                    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
        
        # Diagnostic automatique si activé
        if self.auto_detect_scanned:
            is_scanned = self._is_scanned_pdf(pages_text, total_pages)
            
            if is_scanned:
                logger.warning(f"🔍 PDF scanné détecté")
                
                if self.use_ocr and self.ocr_available:
                    logger.info("🚀 Basculement vers OCR Tesseract...")
                    try:
                        pages_text = self._extract_with_ocr(str(pdf_path), max_pages)
                    except Exception as e:
                        logger.error(f"❌ Échec OCR: {e}")
                        if not pages_text:
                            raise ValueError("Impossible d'extraire le texte du PDF scanné")
                else:
                    if not self.ocr_available:
                        logger.error("❌ PDF scanné mais OCR non disponible")
                        if not pages_text:
                            raise ValueError("PDF scanné détecté mais OCR non disponible")
                    elif not self.use_ocr:
                        logger.error("❌ PDF scanné mais OCR désactivé")
                        if not pages_text:
                            raise ValueError("PDF scanné détecté - activez use_ocr=True")
            else:
                logger.info(f"✅ PDF normal - Extraction réussie ({len(pages_text)}/{total_pages} pages)")
        else:
            logger.info(f"✅ Extraction terminée ({len(pages_text)}/{total_pages} pages) - Détection auto désactivée")
        
        if not pages_text:
            raise ValueError("Aucun texte extrait du PDF")
        
        return pages_text
    
    def _clean_text(self, text: str) -> str:
        """Nettoyage du texte"""
        if not text:
            return ""
        
        text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f]', '', text)
        text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text)
        text = re.sub(r'[ \t]+', ' ', text)
        text = re.sub(r' ?\n ?', '\n', text)
        text = re.sub(r'-\n([a-zàâäéèêëïîôùûü])', r'\1', text, flags=re.IGNORECASE)
        text = re.sub(r'\s+([.,;:!?])', r'\1', text)
        
        return text.strip()
    
    def create_chunks(self, pages_text: List[Tuple[str, int]], source_file: str = "") -> List[DocumentChunk]:
        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:
                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
            
            start = 0
            while start < text_length:
                end = min(start + self.chunk_size, text_length)
                
                if end < text_length:
                    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()
                
                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
                
                next_start = end - self.chunk_overlap
                if next_start <= start + 50:
                    next_start = end
                start = next_start
                
        logger.info(f"✅ {len(chunks)} chunks créés")
        
        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:
        search_window = 100
        search_start = max(start, end - search_window)
        search_end = min(len(text), end + search_window // 2)
        search_text = text[search_start:search_end]
        
        cut_patterns = [
            r'\n\n',
            r'\. [A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]',
            r'\?\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]',
            r'!\s+[A-ZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ]',
            r'\n',
            r'[;:]\s+',
            r',\s+',
            r'\s+'
        ]
        
        best_pos = end
        for pattern in cut_patterns:
            matches = list(re.finditer(pattern, search_text))
            if matches:
                target_pos = end - search_start
                closest_match = min(matches, key=lambda m: abs(m.start() - target_pos))
                candidate_pos = search_start + closest_match.end()
                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:
        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]
        
        # PRÉFIXE POUR MODÈLE E5 (requis pour performances optimales)
        if "e5" in self.model_name.lower():
            texts = [f"passage: {text}" for text in texts]
            logger.info("✅ Préfixe E5 ajouté aux textes (passage:)")
        
        try:
            batch_size = 32
            all_embeddings = []
            
            for i in range(0, len(texts), batch_size):
                batch = texts[i:i + batch_size]
                
                batch_embeddings = self.embedding_model.encode(
                    batch,
                    convert_to_numpy=True,
                    show_progress_bar=False,
                    normalize_embeddings=True
                )
                all_embeddings.append(batch_embeddings)
            
            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:
        logger.info("🔨 Construction de l'index FAISS...")
        n_vectors, dim = embeddings.shape
        
        if n_vectors < 1000:
            index = faiss.IndexFlatIP(dim)
        else:
            nlist = min(100, n_vectors // 10)
            quantizer = faiss.IndexFlatIP(dim)
            index = faiss.IndexIVFFlat(quantizer, dim, nlist)
            index.train(embeddings)
        
        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:
        start_time = time.time()
        logger.info(f"🚀 Début du traitement: {Path(pdf_path).name}")
        
        try:
            pages_text = self.extract_text_from_pdf(pdf_path)
            source_file = Path(pdf_path).name
            self.chunks = self.create_chunks(pages_text, source_file)
            embeddings = self.create_embeddings(self.chunks)
            self.index = self.build_faiss_index(embeddings)
            
            if save_automatically:
                self.save_index()
            
            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")
            
            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]]:
        if self.index is None:
            raise ValueError("Index non initialisé")
        if not query.strip():
            return []
        
        self._initialize_model()
        
        try:
            # PRÉFIXE POUR MODÈLE E5 (requis pour queries)
            search_query = query
            if "e5" in self.model_name.lower():
                search_query = f"query: {query}"
                logger.info(f"🔍 Recherche avec préfixe E5: query: {query}")
            
            query_embedding = self.embedding_model.encode(
                [search_query], 
                convert_to_numpy=True, 
                normalize_embeddings=True
            )
            
            search_k = min(top_k * 2, len(self.chunks), self.index.ntotal)
            scores, indices = self.index.search(query_embedding, search_k)
            
            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)))
            
            return results[:top_k]
            
        except Exception as e:
            logger.error(f"❌ Erreur recherche: {e}")
            return []
    
    def save_index(self, save_dir: Optional[str] = None) -> Path:
        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)
        
        index_file = save_path / "faiss_index.bin"
        faiss.write_index(self.index, str(index_file))
        
        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': '2.2'
        }
        
        metadata_file = save_path / "metadata.pkl"
        with open(metadata_file, 'wb') as f:
            pickle.dump(metadata, f)
        
        logger.info(f"💾 Sauvegarde terminée: {save_path}")
        return save_path
    
    def load_index(self, save_dir: str) -> Dict:
        save_path = Path(save_dir)
        
        if not save_path.exists():
            raise FileNotFoundError(f"Dossier introuvable: {save_path}")
        
        self.index = faiss.read_index(str(save_path / "faiss_index.bin"))
        
        with open(save_path / "metadata.pkl", 'rb') as f:
            metadata = pickle.load(f)
        
        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")
        
        return {
            'chunks_loaded': len(self.chunks),
            'model_name': self.model_name,
            'embedding_dim': self.embedding_dim
        }


if __name__ == "__main__":
    print("=" * 60)
    print("Test Vectorizer avec OCR + Modèle Cross-Lingual")
    print("=" * 60)
    
    try:
        vectorizer = OptimalPDFVectorizer(
            use_ocr=True, 
            ocr_language='fra',
            ocr_dpi=300,
            ocr_preprocessing=True
        )
        print(f"\nVectorizer initialisé")
        print(f"   - Modèle: {vectorizer.model_name}")
        print(f"   - OCR disponible: {vectorizer.ocr_available}")
        print(f"   - Langue: {vectorizer.ocr_language}")
        print(f"   - DPI: {vectorizer.ocr_dpi}")
        print(f"   - Prétraitement: {vectorizer.ocr_preprocessing}")
        print("\n✅ Test réussi - Recherche cross-linguale FR↔EN activée!")
        
    except Exception as e:
        print(f"\nErreur: {e}")
        import traceback
        traceback.print_exc()