RapidFuzz
Matches strings with fast fuzzy comparison.
- Downloads / mo
- 143.8M
- Stars
- 4.2K
- Last release
- 3.14.6
- License
- MIT
Quickstart
from rapidfuzz.distance import Levenshtein print(Levenshtein.editops("spam", "park"))
RapidFuzz examples
def extract_changes(self, original: str, corrected: str) -> List[ExtractedChange]: """ Extract all from→to changes between original and corrected text Args: original: Original text (before correction) corrected: Corrected text (after AI processing) Returns: List of ExtractedChange objects with context and confidence Raises: InputValidationError: If input validation fails CRITICAL FIX (P1-2): Comprehensive input validation to prevent: - DoS attacks from oversized input - Crashes from None/invalid input - Performance issues from malicious input """ # CRITICAL FIX: Validate input types if not isinstance(original, str): raise InputValidationError( f"original must be str, got {type(original).__name__}" ) if not isinstance(corrected, str): raise InputValidationError( f"corrected must be str, got {type(corrected).__name__}" ) # CRITICAL FIX: Validate input length (DoS prevention) if len(original) > MAX_TEXT_LENGTH: raise InputValidationError( f"original text too long ({len(original)} chars). " f"Maximum allowed: {MAX_TEXT_LENGTH}" ) if len(corrected) > MAX_TEXT_LENGTH: raise InputValidationError( f"corrected text too long ({len(corrected)} chars). " f"Maximum allowed: {MAX_TEXT_LENGTH}" ) # CRITICAL FIX: Handle empty strings gracefully if not original and not corrected: logger.debug("Both texts are empty, returning empty changes list") return [] # CRITICAL FIX: Validate text contains valid characters (not binary data) try: # Try to encode/decode to ensure valid text original.encode('utf-8') corrected.encode('utf-8') except UnicodeError as e: raise InputValidationError(f"Invalid text encoding: {e}") from e logger.debug( f"Extracting changes: original={len(original)} chars, " f"corrected={len(corrected)} chars" ) original_tokens = self._tokenize(original) corrected_tokens = self._tokenize(corrected) opcodes = self._coalesce_opcodes(Levenshtein.opcodes( [token for token, _start, _end in original_tokens], [token for token, _start, _end in corrected_tokens], ).as_list()) changes = [] seen: set[tuple[int, str, str]] = set() for tag, i1, i2, j1, j2 in opcodes: if tag != 'equal': original_start, original_end = self._token_span( original_tokens, i1, i2, len(original) ) corrected_start, corrected_end = self._token_span( corrected_tokens, j1, j2, len(corrected) ) learnable = tag == 'replace' if tag == 'insert': ( original_start, original_end, corrected_start, corrected_end, learnable, ) = self._anchor_insert( original_tokens, corrected_tokens, i1, j1, j2, original_start, original_end, corrected_start, corrected_end, ) elif tag == 'delete': ( original_start, original_end, corrected_start, corrected_end, learnable, ) = self._anchor_delete( original_tokens, corrected_tokens, i1, i2, j1, original_start, original_end, corrected_start, corrected_end, ) from_text = original[original_start:original_end] to_text = corrected[corrected_start:corrected_end] if not self._is_material_change(from_text, to_text): continue learnable_length = self._is_learnable_change_length( from_text, to_text ) formatting_only = self._is_formatting_only(from_text, to_text) # Extract context context_before = original[max(0, original_start-20):original_start] context_after = original[ original_end:min(len(original), original_end+20) ] # Classify change type change_type = self._classify_change( tag, from_text, to_text, formatting_only=formatting_only ) # Calculate confidence (based on text similarity and context) confidence = self._calculate_confidence( from_text, to_text, context_before, context_after ) # Keep the exact bytes of an unexpected whitespace/case edit in # history. Ordinary lexical changes still shed boundary space # so their replayable dictionary pair is not indentation-bound. clean_from = from_text if formatting_only else from_text.strip() clean_to = to_text if formatting_only else to_text.strip() key = (original_start, clean_from, clean_to) if key in seen: continue seen.add(key) changes.append(ExtractedChange( from_text=clean_from, to_text=clean_to, context_before=context_before, context_after=context_after, position=original_start, change_type=change_type, confidence=confidence, learnable=( learnable and learnable_length and not formatting_only and bool(clean_from) and bool(clean_to) and self._contains_lexical_text(clean_from) and self._contains_lexical_text(clean_to) ), )) # CRITICAL FIX: Prevent DoS from excessive changes if len(changes) > MAX_CHANGES: raise InputValidationError( "Correction produced more than " f"{MAX_CHANGES} auditable changes; refusing to truncate " "history for modified text" ) logger.debug(f"Extracted {len(changes)} changes") return changes