Template mapping and detecting done

This commit is contained in:
2026-07-14 16:26:49 +05:30
parent 360022820d
commit c725014788
2 changed files with 50 additions and 3 deletions

View File

@@ -0,0 +1,33 @@
import re
from typing import Optional, Union
def sanitize_amount(text: str) -> Optional[float]:
"""
Sanitizes a string representing an amount/number (e.g., "$1,234.56", "€ 50,000", "50 USD")
by removing currency symbols, commas, and other non-numeric characters (except for the decimal separator),
and casts it to a float.
Args:
text (str): The raw extracted text from the document.
Returns:
Optional[float]: The sanitized numeric value, or None if no number could be extracted.
"""
if not text:
return None
# Remove obvious alphabetic currency codes, spaces, and commas
# We keep digits, period, and minus sign
cleaned_text = re.sub(r'[^\d\.-]', '', text)
if not cleaned_text:
return None
try:
# Handle cases where multiple periods or dashes might exist incorrectly
# We just try to cast to float. If the OCR produced something like "1.23.45", this will fail.
# A more robust regex can handle exact capture if needed.
# But this basic cast covers 95% of standard sanitized strings.
return float(cleaned_text)
except ValueError:
return None