ocr-error-senat / README.md
HenriPorteur's picture
Update README.md
62a8944 verified
metadata
license: mit
task_categories:
  - text2text-generation
language:
  - fr

Description

The dataset is sourced from the French Senate's records, available at this link. After segmenting the text into sentences, 200,000 sentences were extracted(160,000 for train, 40,000 for test).

OCR errors are generated using the following script, designed to simulate errors found in certain documents from the French National Library caused by physical constraints (e.g., page curvature).

import random
import re
from typing import Dict, List

class FrenchOCRNoiseGenerator:
    def __init__(self, error_density: float = 0.45):
        self.error_density = max(0.0, min(1.0, error_density))
        # Adjust error type weight distribution
        self.error_config = {
            'diacritics': 0.25,     # Diacritic errors
            'case_swap': 0.15,      # Case swapping
            'symbols': 0.18,        # Symbol substitution
            'number_letter': 0.12,  # Number-letter confusion
            'split_words': 0.08,    # Word splitting errors
            'random_space': 0.10,   # Random spacing
            'hyphen_error': 0.07,   # Hyphen-related errors
            'repeat_char': 0.05     # Character repetition
        }
        # Extended French-specific replacement mapping
        self.french_replace_map: Dict[str, List[str]] = {
            # Diacritic characters
            'é': ['e', '3', '€', 'è', 'ê', 'ë', ' '],
            'è': ['e', '€', 'é', 'ë', '¡'],
            'ê': ['e', 'è', 'ë', 'â'],
            'à': ['a', '@', 'â', 'á', 'ä', 'æ'],
            'ù': ['u', 'û', 'ü', '%'],
            'ç': ['c', '¢', '(', '[', ' '],
            'â': ['a', 'à', 'ä', 'å'],
            'î': ['i', 'ï', '!', '1'],
            'ô': ['o', 'ö', '0', '*'],
            'û': ['u', 'ù', 'ü', 'v'],
            # Uppercase letters
            'É': ['E', '3', '€', 'È'],
            'È': ['E', 'Ê', 'Ë'],
            'À': ['A', '@', 'Â'],
            'Ç': ['C', '¢', ' '],
            # Number-letter confusion
            '0': ['o', 'O', 'Ø', ' '],
            '1': ['l', 'I', '!', '|'],
            '2': ['z', 'Z', 'è'],
            '5': ['s', 'S', '$'],
            '7': ['?', ' ', '~'],
            '9': ['q', 'g', ' '],
            # Special symbols
            '-': ['~', '—', '_', ' ', '.', ''],
            "'": ['`', '’', ',', ' '],
            '’': ["'", '`', ' '],
            ',': ['.', ';', ' '],
            ';': [',', ':', ' ']
        }
        # Common OCR error patterns
        self.ocr_patterns = [
            (r'(.)\1{2,}', lambda m: m.group(1)*random.randint(1,3)),  # Handle repeated characters
            (r'(?i)tion', lambda m: 't10n' if random.random() < 0.3 else m.group()),
            (r'(?i)ment\b', lambda m: 'm'+random.choice(['&', '@', '3'])+'nt')
        ]

    def _apply_diacritic_errors(self, char: str) -> str:
        """Process diacritic-related errors"""
        if char in {'é', 'è', 'ê', 'à', 'ù', 'ç', 'â', 'î', 'ô', 'û'}:
            # 30% chance to remove diacritics completely
            if random.random() < 0.3:
                return char.encode('ascii', 'ignore').decode() or char
            # 70% chance to replace with another diacritic character
            return random.choice(self.french_replace_map.get(char, [char]))
        return char

    def _hyphen_errors(self, text: str) -> str:
        """Handle hyphen-related errors"""
        return re.sub(r'[-—]', lambda m: random.choice(['~', '_', ' ', '.', ''] + ['']*3), text)

    def _apply_ocr_patterns(self, text: str) -> str:
        """Apply predefined OCR error patterns"""
        for pattern, repl in self.ocr_patterns:
            text = re.sub(pattern, repl, text)
        return text

    def _generate_errors(self, char: str) -> str:
        """Core error generation logic"""
        if random.random() > self.error_density:
            return char

        # French-specific processing
        if char in self.french_replace_map:
            return random.choice(self.french_replace_map[char])

        error_type = random.choices(
            list(self.error_config.keys()),
            weights=list(self.error_config.values())
        )[0]

        # Apply different types of errors
        if error_type == 'diacritics':
            return self._apply_diacritic_errors(char)

        elif error_type == 'case_swap' and char.isalpha():
            return char.swapcase() if random.random() < 0.6 else char.lower()

        elif error_type == 'symbols':
            return random.choice(['~', '*', '^', '¡', '¦']) if random.random() < 0.4 else char

        elif error_type == 'number_letter':
            return random.choice(self.french_replace_map.get(char.lower(), [char]))

        elif error_type == 'repeat_char' and char.isalnum():
            return char * random.randint(1,3)

        return char

    def _space_errors(self, text: str) -> str:
        """Optimized space-related errors: more deletions, fewer insertions"""
        # Randomly delete spaces (25% chance to remove any space)
        text = re.sub(r' +', lambda m: ' ' if random.random() > 0.25 else '', text)

        # Randomly add spaces (10% chance to insert a space before a character)
        return re.sub(
            r'(?<! )(?<!^)',
            lambda m: ' ' + m.group() if random.random() < 0.1 else m.group(),
            text
        )

    def add_noise(self, clean_text: str) -> str:
        # Preprocessing: Apply OCR patterns
        noisy_text = self._apply_ocr_patterns(clean_text)

        # Inject character-level errors
        noisy_chars = [self._generate_errors(c) for c in noisy_text]

        # Post-processing steps
        noisy_text = ''.join(noisy_chars)
        noisy_text = self._hyphen_errors(noisy_text)
        noisy_text = self._space_errors(noisy_text)

        # Final cleanup
        return re.sub(r'\s{2,}', ' ', noisy_text).strip()


ocr_generator = FrenchOCRNoiseGenerator(error_density=0.4)
df['OCR Text'] = df['Ground Truth'].apply(ocr_generator.add_noise)