File size: 24,856 Bytes
fe7ff20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import easyocr
from transformers import pipeline
import numpy as np
from PIL import Image
import torch
import re
from datetime import datetime
import PyPDF2
import io
import fitz  # PyMuPDF for better PDF handling
import os

# Set cache directory for transformers
os.environ["TRANSFORMERS_CACHE"] = "/tmp/transformers_cache"

# Check GPU availability
device = 0 if torch.cuda.is_available() else -1
gpu_available = torch.cuda.is_available()

# Initialize EasyOCR reader with multiple languages
reader = easyocr.Reader(['en', 'fr', 'es', 'de'], gpu=gpu_available)

# Initialize summarization pipeline
summarizer = pipeline(
    "summarization",
    model="facebook/bart-large-cnn",
    device=device
)

def extract_metadata(text):
    """
    Extract article metadata from text using pattern matching
    """
    metadata = {
        "title": "Non dรฉtectรฉ",
        "author": "Non dรฉtectรฉ",
        "date": "Non dรฉtectรฉ",
        "location": "Non dรฉtectรฉ"
    }
    
    lines = [line.strip() for line in text.split('\n') if line.strip()]
    
    # Extract Title (usually the first long line)
    for line in lines[:10]:
        if len(line) > 20 and len(line) < 200:
            metadata["title"] = line
            break
    
    # Extract Author - Common patterns
    author_patterns = [
        r'(?:by|par|por|von|de)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,3})',
        r'(?:author|auteur|autor|รฉcrit par):\s*([A-Z][a-z]+(?:\s+[A-Z][a-z]+){1,3})',
        r'^([A-Z][a-z]+\s+[A-Z][a-z]+(?:\s+[A-Z][a-z]+)?)(?:\s*[-โ€“โ€”]|\s*\|)',
    ]
    
    for pattern in author_patterns:
        match = re.search(pattern, text, re.MULTILINE | re.IGNORECASE)
        if match:
            metadata["author"] = match.group(1).strip()
            break
    
    # Extract Date
    date_patterns = [
        r'\b(\d{1,2}[\s/\-\.]\w+[\s/\-\.]\d{2,4})\b',
        r'\b(\w+\s+\d{1,2},?\s+\d{4})\b',
        r'\b(\d{4}[\s/\-\.]\d{1,2}[\s/\-\.]\d{1,2})\b',
        r'\b(\d{1,2}[\s/\-\.]\d{1,2}[\s/\-\.]\d{2,4})\b',
    ]
    
    for pattern in date_patterns:
        match = re.search(pattern, text)
        if match:
            metadata["date"] = match.group(1).strip()
            break
    
    # Extract Location
    location_patterns = [
        r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)?),\s*([A-Z]{2,})\b',
        r'(?:in|ร |en|in)\s+([A-Z][a-z]+(?:,?\s+[A-Z][a-z]+)?)',
    ]
    
    for pattern in location_patterns:
        match = re.search(pattern, text)
        if match:
            if len(match.groups()) > 1:
                metadata["location"] = f"{match.group(1)}, {match.group(2)}"
            else:
                metadata["location"] = match.group(1).strip()
            break
    
    return metadata

def extract_text_from_pdf(pdf_file):
    """
    Extract text from PDF file using PyMuPDF
    """
    try:
        pdf_bytes = pdf_file if isinstance(pdf_file, bytes) else pdf_file.read()
        doc = fitz.open(stream=pdf_bytes, filetype="pdf")
        
        full_text = ""
        page_texts = []
        
        for page_num in range(len(doc)):
            page = doc[page_num]
            text = page.get_text()
            page_texts.append({
                "page_number": page_num + 1,
                "text": text,
                "word_count": len(text.split())
            })
            full_text += f"\n\n--- Page {page_num + 1} ---\n\n{text}"
        
        doc.close()
        return full_text, page_texts, len(doc)
    except Exception as e:
        raise Exception(f"Erreur lors de la lecture du PDF: {str(e)}")

def extract_text_from_images(image_files, progress=gr.Progress()):
    """
    Extract text from multiple images using OCR
    """
    full_text = ""
    page_texts = []
    
    for idx, image_file in enumerate(progress.tqdm(image_files, desc="Traitement des images")):
        try:
            if isinstance(image_file, str):
                image = Image.open(image_file)
            else:
                image = Image.open(image_file.name) if hasattr(image_file, 'name') else Image.open(image_file)
            
            image_array = np.array(image)
            results = reader.readtext(image_array, detail=1)
            
            page_text = " ".join([result[1] for result in results])
            page_texts.append({
                "page_number": idx + 1,
                "text": page_text,
                "word_count": len(page_text.split())
            })
            
            full_text += f"\n\n--- Page {idx + 1} ---\n\n{page_text}"
        except Exception as e:
            page_texts.append({
                "page_number": idx + 1,
                "text": f"Erreur: {str(e)}",
                "word_count": 0
            })
    
    return full_text, page_texts, len(image_files)

def chunk_text_for_summary(text, chunk_size=800):
    """
    Split text into chunks for better summarization of long documents
    """
    words = text.split()
    chunks = []
    for i in range(0, len(words), chunk_size):
        chunk = " ".join(words[i:i + chunk_size])
        chunks.append(chunk)
    return chunks

def generate_hierarchical_summary(text, min_length, max_length):
    """
    Generate a comprehensive summary using hierarchical approach for long documents
    """
    words = text.split()
    word_count = len(words)
    
    if word_count < 30:
        return "โš ๏ธ Texte trop court pour gรฉnรฉrer un rรฉsumรฉ (minimum 30 mots requis)."
    
    try:
        # For very long documents (>3000 words), use multi-stage summarization
        if word_count > 3000:
            # Stage 1: Split into chunks and summarize each
            chunks = chunk_text_for_summary(text, chunk_size=1000)
            chunk_summaries = []
            
            for chunk in chunks[:5]:  # Limit to first 5 chunks for performance
                try:
                    summary = summarizer(
                        chunk,
                        max_length=150,
                        min_length=50,
                        do_sample=False,
                        truncation=True
                    )
                    chunk_summaries.append(summary[0]['summary_text'])
                except:
                    continue
            
            # Stage 2: Combine and summarize the summaries
            combined_summary = " ".join(chunk_summaries)
            if len(combined_summary.split()) > 100:
                final_summary = summarizer(
                    combined_summary,
                    max_length=max_length,
                    min_length=min_length,
                    do_sample=False,
                    truncation=True
                )
                return final_summary[0]['summary_text']
            else:
                return combined_summary
        
        # For medium documents (1000-3000 words)
        elif word_count > 1000:
            text_to_summarize = " ".join(words[:1500])
            max_len = min(max_length, 300)
            min_len = min(min_length, 80)
        
        # For short documents (<1000 words)
        else:
            text_to_summarize = text
            max_len = min(max_length, word_count)
            min_len = min(min_length, word_count // 3)
        
        summary = summarizer(
            text_to_summarize,
            max_length=max_len,
            min_length=min_len,
            do_sample=False,
            truncation=True
        )
        return summary[0]['summary_text']
    
    except Exception as e:
        return f"Erreur lors de la gรฉnรฉration du rรฉsumรฉ: {str(e)}"

def process_document(file_input, file_type, min_summary_length, max_summary_length, progress=gr.Progress()):
    """
    Process uploaded document (PDF or images) and extract all information
    """
    if not file_input:
        return "Veuillez tรฉlรฉcharger un fichier.", "", "", "", "", "", "", "N/A", 0, 0
    
    try:
        progress(0, desc="๐Ÿš€ Dรฉmarrage de l'extraction...")
        
        # Extract text based on file type
        if file_type == "PDF":
            progress(0.1, desc="๐Ÿ“„ Lecture du PDF...")
            full_text, page_texts, num_pages = extract_text_from_pdf(file_input)
            progress(0.4, desc=f"โœ… PDF extrait: {num_pages} pages")
        else:  # Images
            progress(0.1, desc="๐Ÿ–ผ๏ธ Prรฉparation des images...")
            files = file_input if isinstance(file_input, list) else [file_input]
            full_text, page_texts, num_pages = extract_text_from_images(files, progress)
            progress(0.4, desc=f"โœ… {num_pages} images traitรฉes")
        
        if not full_text.strip():
            return "Aucun texte dรฉtectรฉ dans le document.", "", "", "", "", "", "", "N/A", 0, num_pages
        
        progress(0.5, desc="๐Ÿ” Extraction des mรฉtadonnรฉes...")
        
        # Extract metadata
        metadata = extract_metadata(full_text)
        
        # Word count
        total_words = sum([p["word_count"] for p in page_texts])
        
        progress(0.6, desc="๐Ÿ“Š Analyse des pages...")
        
        # Create detailed page summary
        page_summary = "๐Ÿ“ˆ STATISTIQUES PAR PAGE:\n\n"
        page_summary += "\n".join([
            f"๐Ÿ“„ Page {p['page_number']}: {p['word_count']} mots"
            for p in page_texts[:15]  # Show first 15 pages
        ])
        
        if len(page_texts) > 15:
            remaining_pages = len(page_texts) - 15
            remaining_words = sum([p['word_count'] for p in page_texts[15:]])
            page_summary += f"\n\n๐Ÿ“š ... et {remaining_pages} pages supplรฉmentaires ({remaining_words} mots)"
        
        page_summary += f"\n\n๐Ÿ“Š TOTAL: {num_pages} pages | {total_words} mots"
        
        progress(0.7, desc="๐Ÿค– Gรฉnรฉration du rรฉsumรฉ intelligent...")
        
        # Generate comprehensive summary
        summary_text = generate_hierarchical_summary(full_text, min_summary_length, max_summary_length)
        
        progress(0.9, desc="โœจ Finalisation...")
        
        # Calculate confidence (for OCR only)
        confidence = "N/A (PDF)" if file_type == "PDF" else "~85%"
        
        progress(1.0, desc="โœ… Terminรฉ!")
        
        return (
            full_text,
            metadata["title"],
            metadata["author"],
            metadata["date"],
            metadata["location"],
            summary_text,
            page_summary,
            confidence,
            total_words,
            num_pages
        )
    
    except Exception as e:
        return f"โŒ Erreur: {str(e)}", "", "", "", "", "", "", "N/A", 0, 0

def clear_all():
    """Clear all inputs and outputs"""
    return None, "", "", "", "", "", "", "", "N/A", 0, 0

def update_summary_lengths(style):
    """Update summary length sliders based on style"""
    if style == "Concis":
        return 30, 150
    elif style == "ร‰quilibrรฉ":
        return 50, 250
    else:  # Dรฉtaillรฉ
        return 80, 400

def export_results(full_text, title, author, date, location, summary, page_info):
    """Export results to a formatted text file"""
    if not full_text or full_text.startswith("Veuillez") or full_text.startswith("Aucun") or full_text.startswith("โŒ"):
        return None
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"/tmp/document_analysis_{timestamp}.txt"
    
    content = f"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘        ANALYSE DE DOCUMENT - EXTRACTION DE DONNร‰ES           โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

๐Ÿ“ฐ TITRE:
{title}

โœ๏ธ AUTEUR:
{author}

๐Ÿ“… DATE:
{date}

๐Ÿ“ LOCALISATION:
{location}

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”

{page_info}

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”

๐Ÿ“ Rร‰SUMร‰ INTELLIGENT:

{summary}

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”

๐Ÿ“„ TEXTE COMPLET EXTRAIT:

{full_text}

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
Gรฉnรฉrรฉ le: {datetime.now().strftime("%d/%m/%Y ร  %H:%M:%S")}
Par: Extracteur de Documents Multi-Pages v2.0
"""
    
    try:
        # Save to temporary file
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(content)
        return filename
    except Exception as e:
        print(f"Erreur export: {e}")
        return None

# Custom CSS
custom_css = """
.gradio-container {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.upload-area {
    border: 2px dashed #667eea;
    border-radius: 10px;
    padding: 20px;
    background: #f8f9ff;
}
.stat-box {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 12px;
    border-radius: 8px;
    color: white;
    text-align: center;
    font-weight: bold;
}
footer {visibility: hidden}
"""

# Create Gradio interface
with gr.Blocks(title="Extracteur de Documents Multi-Pages", css=custom_css, theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # ๐Ÿ“š Extracteur de Documents Multi-Pages
        ### Analyse complรจte de livres, articles et documents (PDF ou images)
        
        **Formats supportรฉs:**
        - ๐Ÿ“„ PDF (extraction de texte native)
        - ๐Ÿ–ผ๏ธ Images multiples (JPG, PNG) avec OCR
        
        **Informations extraites:**
        - ๐Ÿ“ฐ Titre du document
        - โœ๏ธ Auteur
        - ๐Ÿ“… Date de publication
        - ๐Ÿ“ Localisation
        - ๐Ÿ“ Rรฉsumรฉ automatique complet
        - ๐Ÿ“Š Statistiques par page
        """
    )
    
    with gr.Row():
        gr.Markdown(f"**Statut:** {'๐ŸŸข GPU Activรฉ' if gpu_available else '๐Ÿ”ต Mode CPU'}")
    
    with gr.Tabs() as tabs:
        with gr.TabItem("๐Ÿ“„ Upload PDF"):
            with gr.Row():
                with gr.Column(scale=1):
                    pdf_input = gr.File(
                        label="๐Ÿ“ค Tรฉlรฉcharger un fichier PDF",
                        file_types=[".pdf"],
                        type="binary"
                    )
                    
                    with gr.Accordion("โš™๏ธ Paramรจtres de rรฉsumรฉ", open=True):
                        gr.Markdown("**Contrรดlez la longueur de votre rรฉsumรฉ:**")
                        min_summary_pdf = gr.Slider(
                            minimum=20,
                            maximum=150,
                            value=50,
                            step=10,
                            label="๐Ÿ“ Longueur minimale (mots)",
                            info="Plus court = rรฉsumรฉ concis"
                        )
                        max_summary_pdf = gr.Slider(
                            minimum=100,
                            maximum=500,
                            value=250,
                            step=25,
                            label="๐Ÿ“ Longueur maximale (mots)",
                            info="Plus long = rรฉsumรฉ dรฉtaillรฉ"
                        )
                        
                        summary_style = gr.Radio(
                            choices=["Concis", "ร‰quilibrรฉ", "Dรฉtaillรฉ"],
                            value="ร‰quilibrรฉ",
                            label="๐Ÿ“ Style de rรฉsumรฉ"
                        )
                        
                        summary_style.change(
                            fn=update_summary_lengths,
                            inputs=[summary_style],
                            outputs=[min_summary_pdf, max_summary_pdf]
                        )
                    
                    analyze_pdf_btn = gr.Button("๐Ÿ” Analyser le PDF", variant="primary", size="lg")
        
        with gr.TabItem("๐Ÿ–ผ๏ธ Upload Images"):
            with gr.Row():
                with gr.Column(scale=1):
                    images_input = gr.File(
                        label="๐Ÿ“ค Tรฉlรฉcharger plusieurs images (pages du livre)",
                        file_types=["image"],
                        file_count="multiple"
                    )
                    
                    gr.Markdown(
                        """
                        ๐Ÿ’ก **Conseil:** Nommez vos fichiers dans l'ordre (page1.jpg, page2.jpg, etc.)
                        pour une extraction sรฉquentielle correcte.
                        """
                    )
                    
                    with gr.Accordion("โš™๏ธ Paramรจtres de rรฉsumรฉ", open=True):
                        gr.Markdown("**Contrรดlez la longueur de votre rรฉsumรฉ:**")
                        min_summary_img = gr.Slider(
                            minimum=20,
                            maximum=150,
                            value=50,
                            step=10,
                            label="๐Ÿ“ Longueur minimale (mots)",
                            info="Plus court = rรฉsumรฉ concis"
                        )
                        max_summary_img = gr.Slider(
                            minimum=100,
                            maximum=500,
                            value=250,
                            step=25,
                            label="๐Ÿ“ Longueur maximale (mots)",
                            info="Plus long = rรฉsumรฉ dรฉtaillรฉ"
                        )
                        
                        summary_style_img = gr.Radio(
                            choices=["Concis", "ร‰quilibrรฉ", "Dรฉtaillรฉ"],
                            value="ร‰quilibrรฉ",
                            label="๐Ÿ“ Style de rรฉsumรฉ"
                        )
                        
                        summary_style_img.change(
                            fn=update_summary_lengths,
                            inputs=[summary_style_img],
                            outputs=[min_summary_img, max_summary_img]
                        )
                    
                    analyze_images_btn = gr.Button("๐Ÿ” Analyser les Images", variant="primary", size="lg")
    
    # Statistics Row
    with gr.Row():
        confidence_output = gr.Textbox(
            label="๐Ÿ“Š Confiance",
            value="N/A",
            interactive=False,
            scale=1
        )
        word_count_output = gr.Textbox(
            label="๐Ÿ“ Total Mots",
            value="0",
            interactive=False,
            scale=1
        )
        page_count_output = gr.Textbox(
            label="๐Ÿ“„ Nombre Pages",
            value="0",
            interactive=False,
            scale=1
        )
    
    # Metadata Section
    gr.Markdown("### ๐Ÿ“‹ Mรฉtadonnรฉes Extraites")
    
    with gr.Row():
        title_output = gr.Textbox(
            label="๐Ÿ“ฐ Titre",
            placeholder="Le titre sera extrait automatiquement...",
            lines=2,
            show_copy_button=True,
            scale=2
        )
        author_output = gr.Textbox(
            label="โœ๏ธ Auteur",
            placeholder="L'auteur sera dรฉtectรฉ...",
            show_copy_button=True,
            scale=1
        )
    
    with gr.Row():
        date_output = gr.Textbox(
            label="๐Ÿ“… Date",
            placeholder="Date...",
            show_copy_button=True,
            scale=1
        )
        location_output = gr.Textbox(
            label="๐Ÿ“ Localisation",
            placeholder="Lieu...",
            show_copy_button=True,
            scale=1
        )
    
    # Results Section
    with gr.Row():
        with gr.Column():
            summary_output = gr.Textbox(
                label="๐Ÿ“ Rรฉsumรฉ du Document",
                lines=8,
                placeholder="Le rรฉsumรฉ sera gรฉnรฉrรฉ automatiquement...",
                show_copy_button=True
            )
            
            page_info_output = gr.Textbox(
                label="๐Ÿ“Š Informations par Page",
                lines=6,
                placeholder="Statistiques par page...",
                show_copy_button=True
            )
        
        with gr.Column():
            extracted_output = gr.Textbox(
                label="๐Ÿ“„ Texte Complet Extrait",
                lines=14,
                placeholder="Le texte extrait apparaรฎtra ici...",
                show_copy_button=True
            )
    
    # Export Section
    with gr.Row():
        clear_btn = gr.Button("๐Ÿ—‘๏ธ Effacer Tout", variant="secondary")
        export_btn = gr.Button("๐Ÿ’พ Exporter les Rรฉsultats", variant="secondary")
    
    export_output = gr.File(label="๐Ÿ“ฅ Fichier d'Export")
    
    gr.Markdown(
        """
        ---
        ### ๐Ÿ’ก Conseils pour de meilleurs rรฉsultats:
        
        **Pour les PDF:**
        - โœ… Utilisez des PDF avec texte sรฉlectionnable (pas des scans)
        - โœ… Les PDF natifs donnent de meilleurs rรฉsultats que les PDF scannรฉs
        - โšก Traitement ultra-rapide (quelques secondes pour 100+ pages)
        
        **Pour les Images:**
        - โœ… Images haute rรฉsolution (min. 1200x1600 pixels)
        - โœ… Bon รฉclairage et contraste
        - โœ… Texte bien visible et lisible
        - โœ… Nommez les fichiers dans l'ordre (page1.jpg, page2.jpg...)
        - โฑ๏ธ Comptez ~2-3 secondes par page pour l'OCR
        
        ### ๐ŸŽฏ ร€ propos du rรฉsumรฉ intelligent:
        
        **Rรฉsumรฉ hiรฉrarchique pour longs documents:**
        - ๐Ÿ“š Documents < 1000 mots: Rรฉsumรฉ direct
        - ๐Ÿ“– Documents 1000-3000 mots: Rรฉsumรฉ optimisรฉ
        - ๐Ÿ“• Documents > 3000 mots: Rรฉsumรฉ multi-รฉtapes
          1. Le document est divisรฉ en chunks de 1000 mots
          2. Chaque chunk est rรฉsumรฉ sรฉparรฉment
          3. Les rรฉsumรฉs sont combinรฉs et re-rรฉsumรฉs
          4. Rรฉsultat: un rรฉsumรฉ cohรฉrent et complet
        
        **Styles de rรฉsumรฉ:**
        - ๐ŸŽฏ **Concis**: Points clรฉs essentiels (30-150 mots)
        - โš–๏ธ **ร‰quilibrรฉ**: Vue d'ensemble complรจte (50-250 mots) - Recommandรฉ
        - ๐Ÿ“‹ **Dรฉtaillรฉ**: Analyse approfondie (80-400 mots)
        
        ### โšก Performance:
        - ๐ŸŸข **Mode GPU**: Traitement OCR 5-10x plus rapide
        - ๐Ÿ”ต **Mode CPU**: Fonctionne sur tous les systรจmes
        - ๐Ÿ“Š **Barre de progression**: Suivez chaque รฉtape du traitement
        - ๐Ÿ’พ **Export complet**: Sauvegardez tous les rรฉsultats en un clic
        """
    )
    
    # Event handlers for PDF
    analyze_pdf_btn.click(
        fn=lambda pdf, min_s, max_s: process_document(pdf, "PDF", min_s, max_s),
        inputs=[pdf_input, min_summary_pdf, max_summary_pdf],
        outputs=[
            extracted_output,
            title_output,
            author_output,
            date_output,
            location_output,
            summary_output,
            page_info_output,
            confidence_output,
            word_count_output,
            page_count_output
        ]
    )
    
    # Event handlers for Images
    analyze_images_btn.click(
        fn=lambda imgs, min_s, max_s: process_document(imgs, "Images", min_s, max_s),
        inputs=[images_input, min_summary_img, max_summary_img],
        outputs=[
            extracted_output,
            title_output,
            author_output,
            date_output,
            location_output,
            summary_output,
            page_info_output,
            confidence_output,
            word_count_output,
            page_count_output
        ]
    )
    
    # Clear button
    clear_btn.click(
        fn=clear_all,
        inputs=None,
        outputs=[
            pdf_input,
            extracted_output,
            title_output,
            author_output,
            date_output,
            location_output,
            summary_output,
            page_info_output,
            confidence_output,
            word_count_output,
            page_count_output
        ]
    )
    
    # Export functionality
    export_btn.click(
        fn=export_results,
        inputs=[
            extracted_output,
            title_output,
            author_output,
            date_output,
            location_output,
            summary_output,
            page_info_output
        ],
        outputs=export_output
    )

# Launch the app
if __name__ == "__main__":
    demo.launch(share=True)