File size: 27,019 Bytes
c139f95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py - Gradio Interface for Advanced Multi-Language OCR System
# Hugging Face Spaces compatible application

import os
import json
import shutil
from datetime import datetime
from pathlib import Path
from typing import Tuple
import gradio as gr

# Set up logging first
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Try to import our OCR functionality with error handling
try:
    from main6_pix2text import extract_all_text_advanced_pix2text, initialize_pix2text
    from eval import evaluate_ocr_accuracy, clean_control_characters

    OCR_AVAILABLE = True
    logger.info("โœ… OCR modules imported successfully")
except ImportError as e:
    logger.error(f"โŒ OCR modules not available: {e}")
    OCR_AVAILABLE = False

    # Create dummy functions as fallbacks
    def extract_all_text_advanced_pix2text(*args, **kwargs):
        raise RuntimeError(
            "OCR functionality not available due to missing dependencies"
        )

    def initialize_pix2text():
        return None

    def evaluate_ocr_accuracy(*args, **kwargs):
        raise RuntimeError(
            "Evaluation functionality not available due to missing dependencies"
        )

    def clean_control_characters(text):
        return text


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# Create necessary directories
def create_directories():
    """Create necessary directories for file storage."""
    directories = ["documents", "extracted", "temp"]
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
        logger.info(f"โœ… Created/verified directory: {directory}")


# Initialize directories
create_directories()

# Initialize Pix2Text model at startup with error handling
logger.info("๐Ÿš€ Initializing Pix2Text model...")
if OCR_AVAILABLE:
    try:
        PIX2TEXT_MODEL = initialize_pix2text()
        if PIX2TEXT_MODEL:
            logger.info("โœ… Pix2Text model loaded successfully")
        else:
            logger.warning("โš ๏ธ Pix2Text model not available, using fallback OCR")
    except Exception as e:
        logger.error(f"โŒ Failed to initialize Pix2Text: {e}")
        PIX2TEXT_MODEL = None
else:
    logger.warning("โš ๏ธ OCR modules not available - running in demo mode")
    PIX2TEXT_MODEL = None


def get_safe_filename(filename: str) -> str:
    """Generate a safe filename with timestamp."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    name, ext = os.path.splitext(filename)
    # Remove special characters and replace spaces
    safe_name = "".join(c for c in name if c.isalnum() or c in ("-", "_")).rstrip()
    return f"{safe_name}_{timestamp}{ext}"


def get_extraction_filename(pdf_filename: str, file_type: str) -> str:
    """Generate extraction filename with convention: [pdf_filename]_extract.[extension]"""
    base_name = os.path.splitext(pdf_filename)[0]
    extensions = {"txt": "txt", "json": "json", "analysis": "json"}
    return f"{base_name}_extract.{extensions.get(file_type, 'txt')}"


def extract_text_from_pdf(pdf_file) -> Tuple[str, str, str, str]:
    """
    Extract text from uploaded PDF file using advanced OCR.

    Returns:
        - extracted_text: The full extracted text
        - summary_text: A summary of the extraction process
        - text_file_path: Path to the text file (for download)
        - json_file_path: Path to the JSON file (for download)
    """
    if pdf_file is None:
        return "โŒ No file uploaded", "Please upload a PDF file", "", ""

    try:
        start_time = datetime.now()

        # Get the uploaded file path
        pdf_path = pdf_file.name
        filename = os.path.basename(pdf_path)

        logger.info(f"๐Ÿ“„ Processing uploaded file: {filename}")

        # Generate safe filename
        safe_filename = get_safe_filename(filename)

        # Copy uploaded file to documents directory
        documents_path = Path("documents") / safe_filename
        shutil.copy2(pdf_path, documents_path)

        # Generate output filenames
        text_filename = get_extraction_filename(safe_filename, "txt")
        json_filename = get_extraction_filename(safe_filename, "json")
        analysis_filename = get_extraction_filename(safe_filename, "analysis")

        # Create full paths for extracted files
        text_path = Path("extracted") / text_filename
        json_path = Path("extracted") / json_filename
        analysis_path = Path("extracted") / analysis_filename

        logger.info("๐Ÿ”„ Starting OCR processing...")

        # Check if OCR functionality is available
        if not OCR_AVAILABLE:
            return (
                """โŒ **OCR functionality not available**

This appears to be a demo environment where the OCR dependencies are not fully installed.

**Missing components:**
- OpenCV (cv2) for image processing
- Tesseract OCR for text recognition
- Pix2Text for mathematical expression extraction

**To use this system:**
1. Deploy to Hugging Face Spaces with proper dependencies
2. Or install missing packages locally:
   ```bash
   pip install opencv-python pytesseract pix2text
   apt-get install tesseract-ocr tesseract-ocr-ben poppler-utils
   ```

**Demo Features Available:**
- Interface navigation and design preview
- File upload testing (files are validated but not processed)
- System architecture demonstration
""",
                "OCR dependencies not available in this environment",
                "",
                "",
            )

        # Process the PDF using our advanced OCR system
        extract_all_text_advanced_pix2text(
            pdf_path=str(documents_path),
            output_text_file=str(text_path),
            output_json_file=str(json_path),
            output_analysis_file=str(analysis_path),
        )

        # Read the extracted text
        with open(text_path, "r", encoding="utf-8") as f:
            extracted_text = f.read()

        # Read the analysis for summary
        with open(analysis_path, "r", encoding="utf-8") as f:
            analysis_data = json.load(f)

        # Calculate processing time
        end_time = datetime.now()
        processing_time = (end_time - start_time).total_seconds()

        # Create summary
        summary = f"""
๐Ÿ“Š **OCR Processing Complete!**

โฑ๏ธ **Processing Time:** {processing_time:.2f} seconds
๐Ÿ“„ **Original File:** {filename}
๐Ÿ“ **Extracted Characters:** {len(extracted_text):,}

๐Ÿ”ค **Text Distribution:**
- English regions: {analysis_data.get("type_distribution", {}).get("english", 0)}
- Bangla regions: {analysis_data.get("type_distribution", {}).get("bangla", 0)}
- Math regions: {analysis_data.get("type_distribution", {}).get("math", 0)}
- Mixed regions: {analysis_data.get("type_distribution", {}).get("mixed", 0)}

๐Ÿ“ˆ **Quality Metrics:**
- Total text regions: {analysis_data.get("total_regions", 0)}
- Pages processed: {analysis_data.get("total_pages", 0)}
- Average confidence: {analysis_data.get("confidence_stats", {}).get("avg", 0):.1f}%

๐Ÿ”ง **Extraction Methods:**
- Pix2Text (Math): {analysis_data.get("extraction_methods", {}).get("pix2text", 0)} regions
- Tesseract (Text): {analysis_data.get("extraction_methods", {}).get("tesseract", 0)} regions

โœ… **Status:** Extraction completed successfully!
"""

        logger.info(f"โœ… OCR processing completed in {processing_time:.2f} seconds")

        return extracted_text, summary, str(text_path), str(json_path)

    except Exception as e:
        error_message = f"โŒ **Error during OCR processing:**\n\n{str(e)}"
        logger.error(f"OCR processing failed: {e}")
        return error_message, error_message, "", ""


def evaluate_ocr_files(
    extracted_file, baseline_file, evaluation_name: str = ""
) -> Tuple[str, str]:
    """
    Evaluate OCR accuracy by comparing extracted text with baseline.

    Returns:
        - results_text: Formatted evaluation results
        - summary_text: Summary of the evaluation
    """
    if extracted_file is None or baseline_file is None:
        return "โŒ Please upload both files for evaluation", "Missing files"

    try:
        start_time = datetime.now()

        # Read file contents
        with open(extracted_file.name, "r", encoding="utf-8") as f:
            extracted_text = f.read()

        with open(baseline_file.name, "r", encoding="utf-8") as f:
            baseline_text = f.read()

        logger.info(f"๐Ÿ“Š Starting evaluation: {evaluation_name or 'Unnamed'}")
        logger.info(f"Extracted text length: {len(extracted_text)} characters")
        logger.info(f"Baseline text length: {len(baseline_text)} characters")

        # Check if evaluation functionality is available
        if not OCR_AVAILABLE:
            return (
                """โŒ **Evaluation functionality not available**

This appears to be a demo environment where the evaluation dependencies are not fully installed.

**Missing components:**
- Text processing utilities
- Evaluation algorithms
- Statistical analysis functions

**To use this system:**
1. Deploy to Hugging Face Spaces with proper dependencies
2. Or install missing packages locally

**Demo Features Available:**
- Interface navigation and design preview
- File upload testing (files are validated but not processed)
- System architecture demonstration
""",
                "Evaluation dependencies not available in this environment",
            )

        # Clean input texts
        extracted_text_clean = clean_control_characters(extracted_text)
        baseline_text_clean = clean_control_characters(baseline_text)

        # Perform evaluation
        evaluation_results = evaluate_ocr_accuracy(
            extracted_text=extracted_text_clean,
            baseline_text=baseline_text_clean,
        )

        # Check for evaluation errors
        if "error" in evaluation_results:
            return (
                f"โŒ **Evaluation Error:** {evaluation_results['error']}",
                "Error occurred",
            )

        # Calculate processing time
        end_time = datetime.now()
        processing_time = (end_time - start_time).total_seconds()

        # Format results
        results_text = f"""
๐Ÿ“Š **OCR Evaluation Results**
{f"๐Ÿ“ **Evaluation Name:** {evaluation_name}" if evaluation_name else ""}

๐ŸŽฏ **Overall Performance**
- **Overall Accuracy:** {evaluation_results["overall_accuracy"]:.2f}%
- **Similarity Score:** {evaluation_results["similarity_score"]:.2f}%
- **Grade:** {evaluation_results["evaluation_summary"]["grade"]}

๐Ÿ“ **Character-Level Analysis**
- **Character Accuracy:** {evaluation_results["character_metrics"]["character_accuracy"]:.2f}%
- **Character Error Rate:** {evaluation_results["character_metrics"]["character_error_rate"]:.2f}%
- **Edit Distance:** {evaluation_results["character_metrics"]["edit_distance"]}
- **Total Characters:** {evaluation_results["character_metrics"]["total_characters"]:,}

๐Ÿ“š **Word-Level Analysis**
- **Word Accuracy:** {evaluation_results["word_metrics"]["word_accuracy"]:.2f}%
- **Word Error Rate:** {evaluation_results["word_metrics"]["word_error_rate"]:.2f}%
- **Correct Words:** {evaluation_results["word_metrics"]["correct_words"]} / {evaluation_results["word_metrics"]["total_words"]}
- **Missing Words:** {evaluation_results["word_metrics"]["missing_words"]}
- **Extra Words:** {evaluation_results["word_metrics"]["extra_words"]}

๐Ÿ“„ **Line-Level Analysis**
- **Line Accuracy:** {evaluation_results["line_metrics"]["line_accuracy"]:.2f}%
- **Average Line Similarity:** {evaluation_results["line_metrics"]["average_line_similarity"]:.2f}%
- **Lines Matched:** {evaluation_results["line_metrics"]["lines_matched"]} / {evaluation_results["line_metrics"]["total_lines"]}

๐ŸŒ **Language-Specific Accuracy**
- **English:** {evaluation_results["language_specific"].get("english_accuracy", "N/A")}%
- **Bangla:** {evaluation_results["language_specific"].get("bangla_accuracy", "N/A")}%
- **Mathematics:** {evaluation_results["language_specific"].get("math_accuracy", "N/A")}%
- **Numbers:** {evaluation_results["language_specific"].get("number_accuracy", "N/A")}%

๐Ÿ“ˆ **Text Statistics**
- **Extracted Length:** {evaluation_results["text_statistics"]["extracted_length"]:,} characters
- **Baseline Length:** {evaluation_results["text_statistics"]["baseline_length"]:,} characters
- **Extracted Words:** {evaluation_results["text_statistics"]["extracted_words"]:,}
- **Baseline Words:** {evaluation_results["text_statistics"]["baseline_words"]:,}

๐Ÿ’ก **Recommendations**
"""

        for i, rec in enumerate(
            evaluation_results["evaluation_summary"]["recommendations"], 1
        ):
            results_text += f"{i}. {rec}\n"

        # Create summary
        summary = f"""
๐ŸŽฏ **Evaluation Summary**

โฑ๏ธ **Processing Time:** {processing_time:.3f} seconds
๐Ÿ“Š **Overall Score:** {evaluation_results["overall_accuracy"]:.2f}%
๐Ÿ† **Grade:** {evaluation_results["evaluation_summary"]["grade"]}
๐Ÿ“ **Character Accuracy:** {evaluation_results["character_metrics"]["character_accuracy"]:.2f}%
๐Ÿ“š **Word Accuracy:** {evaluation_results["word_metrics"]["word_accuracy"]:.2f}%

โœ… **Evaluation completed successfully!**
"""

        logger.info(f"โœ… Evaluation completed in {processing_time:.3f} seconds")
        logger.info(
            f"๐Ÿ“Š Overall accuracy: {evaluation_results['overall_accuracy']:.2f}%"
        )

        return results_text, summary

    except Exception as e:
        error_message = f"โŒ **Error during evaluation:**\n\n{str(e)}"
        logger.error(f"Evaluation failed: {e}")
        return error_message, error_message


# Create Gradio interface
def create_gradio_interface():
    """Create and configure the Gradio interface."""

    # Custom CSS for better styling
    css = """
    .gradio-container {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .output-text {
        font-family: 'Courier New', monospace;
        font-size: 14px;
    }
    .summary-box {
        background-color: #f0f8ff;
        border: 1px solid #d0e7ff;
        border-radius: 8px;
        padding: 16px;
        margin: 8px 0;
    }
    """

    with gr.Blocks(
        css=css, title="Advanced Multi-Language OCR System", theme=gr.themes.Soft()
    ) as app:
        # Header
        gr.Markdown("""
        # ๐Ÿ” Advanced Multi-Language OCR System
        
        **Powered by Pix2Text, Tesseract, and FastAPI**
        
        Extract text from PDFs containing **English**, **Bangla**, and **Mathematical expressions** with high accuracy.
        Evaluate OCR performance with comprehensive metrics and detailed analysis.
        """)

        with gr.Tabs():
            # Tab 1: OCR Extraction
            with gr.Tab("๐Ÿ“„ PDF Text Extraction"):
                gr.Markdown("""
                ### Upload a PDF and extract text using advanced multi-language OCR
                
                **Features:**
                - ๐ŸŒ **Multi-language support**: English, Bangla (Bengali), and Mathematical expressions
                - ๐Ÿงฎ **Advanced Math Recognition**: Pix2Text integration for LaTeX and mathematical formulas
                - ๐Ÿ“Š **Detailed Analysis**: Character-level classification and confidence scores
                - ๐Ÿ’พ **Download Results**: Get extracted text and detailed JSON analysis
                """)

                with gr.Row():
                    with gr.Column(scale=1):
                        pdf_input = gr.File(
                            label="๐Ÿ“„ Upload PDF File",
                            file_types=[".pdf"],
                            type="filepath",
                        )
                        extract_btn = gr.Button(
                            "๐Ÿš€ Extract Text", variant="primary", size="lg"
                        )

                    with gr.Column(scale=2):
                        extraction_summary = gr.Textbox(
                            label="๐Ÿ“Š Extraction Summary",
                            lines=15,
                            elem_classes=["summary-box"],
                        )

                with gr.Row():
                    extracted_text_output = gr.Textbox(
                        label="๐Ÿ“ Extracted Text",
                        lines=20,
                        elem_classes=["output-text"],
                        show_copy_button=True,
                    )

                with gr.Row():
                    text_file_download = gr.File(
                        label="๐Ÿ“ฅ Download Text File", visible=False
                    )
                    json_file_download = gr.File(
                        label="๐Ÿ“ฅ Download JSON Analysis", visible=False
                    )

                # Connect extraction functionality
                extract_btn.click(
                    fn=extract_text_from_pdf,
                    inputs=[pdf_input],
                    outputs=[
                        extracted_text_output,
                        extraction_summary,
                        text_file_download,
                        json_file_download,
                    ],
                ).then(
                    lambda text_path, json_path: (
                        gr.update(
                            visible=bool(text_path),
                            value=text_path if text_path else None,
                        ),
                        gr.update(
                            visible=bool(json_path),
                            value=json_path if json_path else None,
                        ),
                    ),
                    inputs=[text_file_download, json_file_download],
                    outputs=[text_file_download, json_file_download],
                )

            # Tab 2: OCR Evaluation
            with gr.Tab("๐Ÿ“Š OCR Accuracy Evaluation"):
                gr.Markdown("""
                ### Compare OCR extracted text with ground truth baseline for accuracy analysis
                
                **Evaluation Features:**
                - ๐ŸŽฏ **Character-level accuracy**: Precise character matching and edit distance
                - ๐Ÿ“š **Word-level accuracy**: Word matching and error rates  
                - ๐Ÿ“„ **Line-level accuracy**: Line comparison and similarity scores
                - ๐ŸŒ **Language-specific metrics**: Separate accuracy for English, Bangla, and Math
                - ๐Ÿ† **Grading system**: Letter grades from A+ to F with recommendations
                """)

                with gr.Row():
                    with gr.Column():
                        extracted_file_input = gr.File(
                            label="๐Ÿ“„ OCR Extracted Text File (.txt)",
                            file_types=[".txt"],
                            type="filepath",
                        )
                        baseline_file_input = gr.File(
                            label="๐Ÿ“‘ Ground Truth Baseline File (.txt)",
                            file_types=[".txt"],
                            type="filepath",
                        )
                        evaluation_name_input = gr.Textbox(
                            label="๐Ÿ“ Evaluation Name (Optional)",
                            placeholder="e.g., Math Document Test #1",
                        )
                        evaluate_btn = gr.Button(
                            "๐Ÿ“Š Evaluate Accuracy", variant="primary", size="lg"
                        )

                    with gr.Column():
                        evaluation_summary = gr.Textbox(
                            label="๐ŸŽฏ Evaluation Summary",
                            lines=10,
                            elem_classes=["summary-box"],
                        )

                with gr.Row():
                    evaluation_results = gr.Textbox(
                        label="๐Ÿ“ˆ Detailed Evaluation Results",
                        lines=25,
                        elem_classes=["output-text"],
                        show_copy_button=True,
                    )

                # Connect evaluation functionality
                evaluate_btn.click(
                    fn=evaluate_ocr_files,
                    inputs=[
                        extracted_file_input,
                        baseline_file_input,
                        evaluation_name_input,
                    ],
                    outputs=[evaluation_results, evaluation_summary],
                )

            # Tab 3: About & Help
            with gr.Tab("โ„น๏ธ About & Help"):
                gr.Markdown("""
                ## ๐Ÿ” Advanced Multi-Language OCR System
                
                This application provides state-of-the-art Optical Character Recognition (OCR) for documents containing mixed languages and mathematical expressions.
                
                ### ๐ŸŒŸ Key Features
                
                #### ๐Ÿ“„ **PDF Text Extraction**
                - **Multi-language Support**: Simultaneously process English and Bangla (Bengali) text
                - **Mathematical Recognition**: Advanced extraction of mathematical formulas and equations using Pix2Text
                - **Intelligent Classification**: Automatic detection and classification of text regions by language/content type
                - **High Accuracy**: Optimized preprocessing and multiple OCR engines for best results
                - **Detailed Analysis**: Character-by-character analysis with confidence scores and language distribution
                
                #### ๐Ÿ“Š **OCR Accuracy Evaluation**
                - **Comprehensive Metrics**: Character, word, and line-level accuracy measurements
                - **Language-Specific Analysis**: Separate accuracy scores for different languages and mathematical content
                - **Edit Distance Calculation**: Precise measurement of text differences using Levenshtein distance
                - **Grading System**: Letter grades (A+ to F) with improvement recommendations
                - **Detailed Comparison**: Side-by-side diff analysis showing insertions, deletions, and matches
                
                ### ๐Ÿ› ๏ธ **Technology Stack**
                
                - **Pix2Text**: Advanced mathematical expression recognition
                - **Tesseract OCR**: Multi-language text recognition with Bengali support
                - **OpenCV**: Image preprocessing and enhancement
                - **PDF2Image**: High-quality PDF to image conversion
                - **FastAPI**: RESTful API backend
                - **Gradio**: Interactive web interface
                
                ### ๐Ÿ“ **Usage Instructions**
                
                #### **For PDF Text Extraction:**
                1. Upload a PDF file using the file picker
                2. Click "๐Ÿš€ Extract Text" to start processing
                3. Review the extraction summary for statistics
                4. Copy the extracted text or download the files
                5. Download the JSON file for detailed analysis data
                
                #### **For OCR Evaluation:**
                1. Upload the OCR-extracted text file (what you want to evaluate)
                2. Upload the ground truth baseline file (the correct text)
                3. Optionally provide an evaluation name for identification
                4. Click "๐Ÿ“Š Evaluate Accuracy" to run the comparison
                5. Review the detailed metrics and recommendations
                
                ### ๐ŸŽฏ **Accuracy Grading System**
                
                - **A+ (95-100%)**: Excellent - Professional-grade accuracy
                - **A (90-94%)**: Very Good - High-quality results with minor errors
                - **B (80-89%)**: Good - Acceptable for most applications
                - **C (70-79%)**: Fair - May require manual review
                - **D (60-69%)**: Poor - Significant improvements needed
                - **F (<60%)**: Very Poor - Major issues requiring attention
                
                ### ๐Ÿ“š **Supported Languages & Content**
                
                - **English**: Full Latin alphabet with punctuation and symbols
                - **Bangla (Bengali)**: Complete Bengali Unicode range (U+0980-U+09FF)
                - **Mathematical Expressions**: 
                  - Basic arithmetic operators (+, -, ร—, รท, =)
                  - Greek letters (ฮฑ, ฮฒ, ฮณ, ฮด, ฯ€, ฮธ, ฮป, ฮผ, ฮฉ, etc.)
                  - Mathematical symbols (โˆ‘, โˆซ, โˆš, โˆž, โˆ‚, โ†’, โ‰ค, โ‰ฅ, etc.)
                  - Subscripts and superscripts
                  - Functions and equations
                  - LaTeX-style expressions
                
                ### ๐Ÿ”ง **Tips for Best Results**
                
                1. **PDF Quality**: Use high-resolution PDFs (300+ DPI) for better accuracy
                2. **Text Clarity**: Ensure text is not blurry, skewed, or low contrast
                3. **Language Consistency**: Mixed-language documents work best when languages are clearly separated
                4. **Mathematical Content**: Complex equations may require manual verification
                5. **File Size**: Larger documents may take longer to process
                
                ### ๐Ÿ› **Troubleshooting**
                
                - **Empty Results**: Check if the PDF contains selectable text or if images need OCR
                - **Low Accuracy**: Try preprocessing the PDF to improve image quality
                - **Mixed Languages**: Ensure the document has clear language boundaries
                - **Mathematical Errors**: Complex formulas may need manual correction
                
                ### ๐Ÿ“ž **Support & Feedback**
                
                For issues, suggestions, or contributions, please visit our [GitHub repository](https://github.com/ashfaqbracu/aaladinai).
                
                ---
                
                **Made with โค๏ธ for advancing multilingual text recognition**
                """)

        # Footer
        gr.Markdown("""
        ---
        
        **๐Ÿ”— Links:** [GitHub Repository](https://github.com/ashfaqbracu/aaladinai) | [Documentation](https://github.com/ashfaqbracu/aaladinai#readme)
        
        **โšก Powered by:** Pix2Text โ€ข Tesseract OCR โ€ข OpenCV โ€ข FastAPI โ€ข Gradio
        """)

    return app


# Main execution
if __name__ == "__main__":
    logger.info("๐Ÿš€ Starting Advanced Multi-Language OCR Gradio Interface...")

    # Create and launch the interface
    app = create_gradio_interface()

    # Launch configuration
    app.launch(
        server_name="0.0.0.0",  # Allow external access for Hugging Face Spaces
        server_port=7860,  # Standard port for Hugging Face Spaces
        share=False,  # Don't create gradio.live link
        show_error=True,  # Show detailed error messages
        max_threads=4,  # Limit concurrent requests
    )