gladia-normalization 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. gladia_normalization-0.1.0.dist-info/METADATA +210 -0
  2. gladia_normalization-0.1.0.dist-info/RECORD +72 -0
  3. gladia_normalization-0.1.0.dist-info/WHEEL +4 -0
  4. gladia_normalization-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. normalization/__init__.py +4 -0
  6. normalization/constants/__init__.py +3 -0
  7. normalization/constants/protectors.py +24 -0
  8. normalization/languages/__init__.py +7 -0
  9. normalization/languages/base/__init__.py +7 -0
  10. normalization/languages/base/language_config.py +83 -0
  11. normalization/languages/base/language_operator.py +65 -0
  12. normalization/languages/english/__init__.py +7 -0
  13. normalization/languages/english/number_normalizer.py +433 -0
  14. normalization/languages/english/operators.py +199 -0
  15. normalization/languages/english/replacements.py +1774 -0
  16. normalization/languages/english/sentence_replacements.py +3 -0
  17. normalization/languages/french/__init__.py +7 -0
  18. normalization/languages/french/operators.py +38 -0
  19. normalization/languages/french/replacements.py +1 -0
  20. normalization/languages/registry.py +17 -0
  21. normalization/pipeline/__init__.py +0 -0
  22. normalization/pipeline/base.py +120 -0
  23. normalization/pipeline/loader.py +70 -0
  24. normalization/pipeline/replacer.py +38 -0
  25. normalization/presets/gladia-3.yaml +119 -0
  26. normalization/steps/__init__.py +4 -0
  27. normalization/steps/base/__init__.py +6 -0
  28. normalization/steps/base/protect_step.py +24 -0
  29. normalization/steps/base/restore_step.py +23 -0
  30. normalization/steps/base/text_step.py +11 -0
  31. normalization/steps/base/word_step.py +11 -0
  32. normalization/steps/registry.py +26 -0
  33. normalization/steps/text/__init__.py +79 -0
  34. normalization/steps/text/apply_sentence_level_replacements.py +29 -0
  35. normalization/steps/text/casefold_text.py +13 -0
  36. normalization/steps/text/convert_comparison_operators_to_words.py +26 -0
  37. normalization/steps/text/convert_decimal_periods_to_decimal_word.py +30 -0
  38. normalization/steps/text/convert_degree_symbols_to_words.py +26 -0
  39. normalization/steps/text/convert_digit_word_sequences_to_digits.py +41 -0
  40. normalization/steps/text/convert_dots_to_words_in_technical_contexts.py +33 -0
  41. normalization/steps/text/convert_oclock_to_numeric_time.py +34 -0
  42. normalization/steps/text/convert_roman_numerals_to_digits.py +41 -0
  43. normalization/steps/text/convert_word_based_time_patterns.py +70 -0
  44. normalization/steps/text/expand_alphanumeric_codes.py +64 -0
  45. normalization/steps/text/expand_contractions.py +16 -0
  46. normalization/steps/text/expand_written_numbers_to_digits.py +13 -0
  47. normalization/steps/text/expand_www_abbreviation.py +15 -0
  48. normalization/steps/text/fix_ampm_letter_spacing.py +25 -0
  49. normalization/steps/text/fix_dot_adjacent_number_words.py +37 -0
  50. normalization/steps/text/fix_one_word_in_numeric_contexts.py +16 -0
  51. normalization/steps/text/fix_version_number_v_prefix.py +15 -0
  52. normalization/steps/text/format_time_patterns_with_ampm.py +53 -0
  53. normalization/steps/text/normalize_numeric_time_formats.py +16 -0
  54. normalization/steps/text/normalize_punctuation_between_number_words.py +30 -0
  55. normalization/steps/text/placeholders.py +367 -0
  56. normalization/steps/text/protect_plus_word_before_digit_words.py +37 -0
  57. normalization/steps/text/remove_acronym_periods.py +17 -0
  58. normalization/steps/text/remove_diacritics.py +40 -0
  59. normalization/steps/text/remove_filler_words.py +19 -0
  60. normalization/steps/text/remove_hash_before_numbers.py +15 -0
  61. normalization/steps/text/remove_non_numeric_trailing_dots.py +15 -0
  62. normalization/steps/text/remove_spaces_between_adjacent_digits.py +54 -0
  63. normalization/steps/text/remove_standalone_currency_symbols.py +35 -0
  64. normalization/steps/text/remove_symbols.py +24 -0
  65. normalization/steps/text/remove_thousand_separators.py +24 -0
  66. normalization/steps/text/remove_trailing_apostrophe_space.py +15 -0
  67. normalization/steps/text/remove_trailing_dot_word_from_emails.py +22 -0
  68. normalization/steps/text/remove_trailing_period.py +15 -0
  69. normalization/steps/text/remove_zero_minutes_from_time.py +30 -0
  70. normalization/steps/text/replace_currency.py +31 -0
  71. normalization/steps/word/__init__.py +3 -0
  72. normalization/steps/word/apply_word_replacements.py +33 -0
@@ -0,0 +1,3 @@
1
+ ENGLISH_SENTENCE_REPLACEMENTS: dict[str, str] = {
2
+ "good bye": "goodbye",
3
+ }
@@ -0,0 +1,7 @@
1
+ from .operators import FrenchOperators
2
+ from .replacements import FRENCH_REPLACEMENTS
3
+
4
+ __all__ = [
5
+ "FrenchOperators",
6
+ "FRENCH_REPLACEMENTS",
7
+ ]
@@ -0,0 +1,38 @@
1
+ from normalization.languages.base import (
2
+ LanguageConfig,
3
+ LanguageOperators,
4
+ )
5
+ from normalization.languages.registry import register_language
6
+
7
+ FRENCH_CONFIG = LanguageConfig(
8
+ code="fr",
9
+ decimal_separator=",",
10
+ decimal_word="virgule",
11
+ thousand_separator=" ",
12
+ symbols_to_words={
13
+ "@": "arobase",
14
+ ".": "point",
15
+ "+": "plus",
16
+ "=": "égal à",
17
+ ">": "plus grand que",
18
+ "<": "plus petit que",
19
+ "°": "degré",
20
+ "°C": "degrés celsius",
21
+ "°F": "degrés fahrenheit",
22
+ "%": "pourcent",
23
+ },
24
+ currency_symbol_to_word={
25
+ "€": "euros",
26
+ "$": "dollars",
27
+ "£": "livres",
28
+ "¢": "cents",
29
+ "¥": "yens",
30
+ },
31
+ filler_words=["euh", "hum", "beh", "bah", "ben", "hein"],
32
+ )
33
+
34
+
35
+ @register_language
36
+ class FrenchOperators(LanguageOperators):
37
+ def __init__(self):
38
+ super().__init__(FRENCH_CONFIG)
@@ -0,0 +1 @@
1
+ FRENCH_REPLACEMENTS: dict[str, str] = {}
@@ -0,0 +1,17 @@
1
+ from typing import Any
2
+
3
+ _LANGUAGE_REGISTRY: dict[str, Any] = {}
4
+
5
+
6
+ def register_language(cls):
7
+ """Decorator that auto-registers a language operators class by its config code."""
8
+ instance = cls()
9
+ assert instance.config.code not in _LANGUAGE_REGISTRY, (
10
+ f"Language code '{instance.config.code}' is already registered"
11
+ )
12
+ _LANGUAGE_REGISTRY[instance.config.code] = cls
13
+ return cls
14
+
15
+
16
+ def get_language_registry() -> dict[str, Any]:
17
+ return _LANGUAGE_REGISTRY
File without changes
@@ -0,0 +1,120 @@
1
+ import re
2
+ from dataclasses import dataclass, field
3
+
4
+ from normalization.constants.protectors import PLACEHOLDER_FALLBACK_CHARS
5
+ from normalization.languages.base import LanguageOperators
6
+ from normalization.steps.base import TextStep, WordStep
7
+
8
+
9
+ @dataclass
10
+ class NormalizationPipeline:
11
+ """
12
+ Ordered, composable normalization pipeline.
13
+
14
+ Structure mirrors the proven 3-stage approach, but each stage
15
+ is now an explicit, inspectable list of steps.
16
+ """
17
+
18
+ name: str
19
+ operators: LanguageOperators
20
+
21
+ # Stage 1: full-text preprocessing
22
+ text_pre_steps: list[TextStep] = field(default_factory=list)
23
+
24
+ # Stage 2: per-word processing
25
+ word_steps: list[WordStep] = field(default_factory=list)
26
+
27
+ # Stage 3: full-text postprocessing
28
+ text_post_steps: list[TextStep] = field(default_factory=list)
29
+
30
+ def normalize(self, text: str) -> str:
31
+ # Normalize whitespace
32
+ text = re.sub(r"\s+", " ", text).strip()
33
+
34
+ # Stage 1
35
+ for step in self.text_pre_steps:
36
+ text = step(text, self.operators)
37
+
38
+ # Stage 2
39
+ words = text.split(" ")
40
+ words = [
41
+ self._apply_word_steps(w)
42
+ for w in words
43
+ if w # drop empty tokens
44
+ ]
45
+ text = " ".join(words)
46
+
47
+ # Stage 3
48
+ for step in self.text_post_steps:
49
+ text = step(text, self.operators)
50
+
51
+ # Restore any placeholders that dedicated steps left behind
52
+ for placeholder, char in PLACEHOLDER_FALLBACK_CHARS.items():
53
+ text = re.sub(
54
+ rf"\s*{re.escape(placeholder)}\s*",
55
+ char,
56
+ text,
57
+ flags=re.IGNORECASE,
58
+ )
59
+
60
+ return re.sub(r"\s+", " ", text).strip()
61
+
62
+ def _apply_word_steps(self, word: str) -> str:
63
+ for step in self.word_steps:
64
+ word = step(word, self.operators)
65
+ return word
66
+
67
+ def validate(self) -> None:
68
+ """
69
+ Enforce pipeline structural constraints.
70
+
71
+ Validates placeholder protect/restore pairing: every protect step in
72
+ text_pre_steps must have its matching restore step(s) in text_post_steps.
73
+ Updated in tandem with steps/text/placeholders.py.
74
+ """
75
+ # Maps each protect step name to the set of restore step names it requires.
76
+ # Updated when protect/restore pairs are added to steps/text/placeholders.py.
77
+ _PROTECT_REQUIRES: dict[str, set[str]] = {
78
+ "protect_email_symbols": {
79
+ "restore_email_at_symbol_with_word",
80
+ "restore_email_dot_symbol_with_word",
81
+ },
82
+ "protect_phone_plus_symbol": {"restore_phone_plus_symbol"},
83
+ "protect_time_colon": {"restore_time_colon"},
84
+ "protect_unit_decimal": {"restore_unit_decimal_as_word"},
85
+ "protect_unit_slash": {"restore_unit_slash"},
86
+ "protect_number_separator_commas": {"remove_number_separator_markers"},
87
+ "protect_decimal_separator": {"restore_decimal_separator_with_word"},
88
+ "protect_hyphenated_letter_spelling": {"remove_letter_spelling_markers"},
89
+ "protect_space_separated_letter_spelling": {
90
+ "remove_letter_spelling_markers"
91
+ },
92
+ }
93
+
94
+ pre_step_names = {s.name for s in self.text_pre_steps}
95
+ post_step_names = {s.name for s in self.text_post_steps}
96
+
97
+ errors: list[str] = []
98
+ for protect_name, required_restores in _PROTECT_REQUIRES.items():
99
+ if protect_name in pre_step_names:
100
+ missing = required_restores - post_step_names
101
+ if missing:
102
+ errors.append(
103
+ f"'{protect_name}' requires restore step(s) in text_post: {sorted(missing)}"
104
+ )
105
+
106
+ if errors:
107
+ raise ValueError(
108
+ f"Pipeline '{self.name}' failed validation:\n"
109
+ + "\n".join(f" - {e}" for e in errors)
110
+ )
111
+
112
+ def describe(self) -> dict:
113
+ """Introspect the pipeline — useful for debugging and docs."""
114
+ return {
115
+ "name": self.name,
116
+ "language": self.operators.config.code,
117
+ "text_pre_steps": [s.name for s in self.text_pre_steps],
118
+ "word_steps": [s.name for s in self.word_steps],
119
+ "text_post_steps": [s.name for s in self.text_post_steps],
120
+ }
@@ -0,0 +1,70 @@
1
+ from pathlib import Path
2
+ from typing import cast
3
+
4
+ import yaml
5
+
6
+ import normalization.languages # noqa: F401 — triggers @register_language decorators
7
+ from normalization.languages.registry import get_language_registry
8
+ from normalization.pipeline.base import NormalizationPipeline
9
+ from normalization.steps import get_step_registry
10
+ from normalization.steps.base import TextStep, WordStep
11
+
12
+ _PRESETS_DIR = Path(__file__).parent.parent / "presets"
13
+
14
+
15
+ def _resolve_preset_path(preset: str | Path) -> Path:
16
+ path = Path(preset)
17
+ if path.exists() and path.is_file():
18
+ return path
19
+ if path.suffix in (".yaml", ".yml"):
20
+ raise FileNotFoundError(f"Preset file not found: {path}")
21
+ yaml_path = _PRESETS_DIR / f"{preset}.yaml"
22
+ if not yaml_path.exists():
23
+ available = [p.stem for p in _PRESETS_DIR.glob("*.yaml")]
24
+ raise FileNotFoundError(
25
+ f"No built-in preset named {preset!r}. Available presets: {available}"
26
+ )
27
+ return yaml_path
28
+
29
+
30
+ def load_pipeline(preset: str | Path, language: str) -> NormalizationPipeline:
31
+ """
32
+ Load a pipeline for a given language.
33
+
34
+ ``preset`` can be:
35
+
36
+ - A preset name (e.g. ``"gladia-3"``): loads the corresponding YAML from
37
+ the package's built-in ``presets/`` directory.
38
+ - A path to a YAML file (e.g. ``"path/to/my-preset.yaml"``): loads that
39
+ file directly.
40
+
41
+ Step ORDER within each stage is defined by the YAML list order,
42
+ but the 3-stage structure (pre / word / post) is enforced.
43
+ """
44
+ config = yaml.safe_load(_resolve_preset_path(preset).read_text())
45
+
46
+ language_registry = get_language_registry()
47
+ operators = language_registry.get(language, language_registry["default"])()
48
+
49
+ def resolve_steps(step_names: list[str], registry_key: str):
50
+ registry = get_step_registry()[registry_key]
51
+ return [registry[name]() for name in step_names]
52
+
53
+ pipeline = NormalizationPipeline(
54
+ name=config["name"],
55
+ operators=operators,
56
+ text_pre_steps=cast(
57
+ list[TextStep],
58
+ resolve_steps(config.get("stages", {}).get("text_pre", []), "text"),
59
+ ),
60
+ word_steps=cast(
61
+ list[WordStep],
62
+ resolve_steps(config.get("stages", {}).get("word", []), "word"),
63
+ ),
64
+ text_post_steps=cast(
65
+ list[TextStep],
66
+ resolve_steps(config.get("stages", {}).get("text_post", []), "text"),
67
+ ),
68
+ )
69
+ pipeline.validate()
70
+ return pipeline
@@ -0,0 +1,38 @@
1
+ import logging
2
+ import re
3
+
4
+ logger = logging.getLogger(__name__)
5
+
6
+
7
+ class Replacer:
8
+ """Stateful compiled-regex engine for word-level replacements.
9
+
10
+ Pre-compiles one \\b-bounded pattern per mapping entry at init time.
11
+ At least one side of each mapping pair must be a single word.
12
+ """
13
+
14
+ def __init__(self, mapping: dict[str, str]):
15
+ patterns: dict[re.Pattern, str] = {}
16
+ for left, right in mapping.items():
17
+ left_is_single = len(left.strip().split()) == 1
18
+ right_is_single = len(right.strip().split()) == 1
19
+
20
+ if not left_is_single and not right_is_single:
21
+ logger.warning(
22
+ f"At least one side must be a single word: '{left}' - '{right}'"
23
+ )
24
+ continue
25
+
26
+ if left_is_single:
27
+ bad, good = left, right
28
+ else:
29
+ bad, good = right, left
30
+
31
+ patterns[re.compile(rf"\b{re.escape(bad)}\b")] = good
32
+
33
+ self.patterns = patterns
34
+
35
+ def __call__(self, text: str) -> str:
36
+ for pattern, replacement in self.patterns.items():
37
+ text = pattern.sub(replacement, text)
38
+ return text
@@ -0,0 +1,119 @@
1
+ name: gladia-3
2
+
3
+ stages:
4
+ text_pre:
5
+ # --- Phase 1: Protect symbols from being erased by later cleanup ---
6
+ # Run first so that email @/., phone +, time :, unit decimal/slash, and
7
+ # number separators all survive remove_symbols later in this stage.
8
+ - protect_email_symbols
9
+ - protect_phone_plus_symbol
10
+ - protect_time_colon
11
+ - protect_unit_decimal
12
+ - protect_unit_slash
13
+ - protect_number_separator_commas
14
+
15
+ # --- Phase 2: Pre-casefold transforms ---
16
+ # These steps rely on original casing (degree symbols, acronyms) or must
17
+ # run before contractions alter token boundaries.
18
+ - remove_hash_before_numbers
19
+ - normalize_numeric_time_formats
20
+ - convert_degree_symbols_to_words
21
+ - convert_oclock_to_numeric_time
22
+ - remove_acronym_periods
23
+ # Protect spelled-out letters (b-o-b, j o h n) before any word transform
24
+ # can misinterpret individual letters as real words.
25
+ - protect_hyphenated_letter_spelling
26
+ - protect_space_separated_letter_spelling
27
+ - apply_sentence_level_replacements
28
+ - expand_contractions
29
+
30
+ # --- Phase 3: Numeric transforms (before written-number expansion) ---
31
+ - protect_plus_word_before_digit_words
32
+ - convert_comparison_operators_to_words
33
+ # convert_word_based_time_patterns creates new HH:MM tokens; protect_time_colon
34
+ # runs a second time immediately after to cover those new patterns.
35
+ - convert_word_based_time_patterns
36
+ - protect_time_colon # 2nd run: covers HH:MM produced by the step above
37
+ - remove_thousand_separators
38
+ - convert_dots_to_words_in_technical_contexts
39
+ # protect_decimal_separator runs here for the first time (decimal patterns
40
+ # only become distinct from thousand-separators after remove_thousand_separators).
41
+ # protect_number_separator_commas runs a second time to cover any new
42
+ # comma-separated digit groups exposed by the numeric transforms above.
43
+ - protect_decimal_separator
44
+ - protect_number_separator_commas # 2nd run
45
+ - normalize_punctuation_between_number_words
46
+ - convert_digit_word_sequences_to_digits
47
+
48
+ # --- Phase 4: Written-number expansion ---
49
+ - expand_written_numbers_to_digits
50
+ # Re-protect after expansion: expand_written_numbers_to_digits can produce
51
+ # new decimal numbers (e.g. "three point five" → "3.5"), new phone-number-
52
+ # like digit sequences, and new email-adjacent patterns. All must be
53
+ # protected before remove_symbols erases the separators.
54
+ - protect_decimal_separator # 2nd run
55
+ - protect_phone_plus_symbol # 2nd run
56
+ - protect_email_symbols # 2nd run
57
+ - protect_number_separator_commas # 3rd run
58
+
59
+ # --- Phase 5: Code and abbreviation expansion ---
60
+ # convert_roman_numerals_to_digits must run before expand_alphanumeric_codes
61
+ # to prevent "VIII" from being spaced out to "V I I I" instead of "8".
62
+ - expand_www_abbreviation
63
+ - convert_roman_numerals_to_digits
64
+ - expand_alphanumeric_codes
65
+
66
+ # --- Phase 6: Casefold and cleanup ---
67
+ - casefold_text
68
+ - remove_symbols
69
+ - remove_diacritics
70
+ - remove_standalone_currency_symbols
71
+ # remove_filler_words runs after casefold so that mixed-case fillers
72
+ # (e.g. "Um", "UH") are matched reliably against the lowercase config list.
73
+ - remove_filler_words
74
+
75
+ word:
76
+ - apply_word_replacements
77
+
78
+ text_post:
79
+ # --- Phase 1: Restore protected symbols and resolve placeholders ---
80
+ - restore_email_at_symbol_with_word
81
+ - restore_email_dot_symbol_with_word
82
+ - restore_time_colon
83
+ - replace_currency
84
+ - restore_unit_decimal_as_word
85
+ # fix_dot_adjacent_number_words must run before restore_decimal_separator
86
+ # so that "zero dot one" → "0 dot 1" is done while "dot" is still a word.
87
+ - fix_dot_adjacent_number_words
88
+ - fix_version_number_v_prefix
89
+ - restore_decimal_separator_with_word
90
+ - convert_decimal_periods_to_decimal_word
91
+ - remove_trailing_apostrophe_space
92
+ - remove_non_numeric_trailing_dots
93
+
94
+ # --- Phase 2: Time and digit collapsing ---
95
+ - format_time_patterns_with_ampm
96
+ # First digit-collapse pass: collapses within each number-separator-bounded
97
+ # group independently before the markers are removed.
98
+ - remove_spaces_between_adjacent_digits
99
+ - fix_one_word_in_numeric_contexts
100
+ # Removing markers may join previously separated digit groups; collapse
101
+ # spaces again immediately after so those groups are merged correctly.
102
+ - remove_number_separator_markers
103
+ - remove_spaces_between_adjacent_digits # 2nd run: after marker removal
104
+
105
+ # --- Phase 3: Late restores (must follow digit collapsing) ---
106
+ - restore_phone_plus_symbol
107
+ # fix_ampm_letter_spacing and remove_letter_spelling_markers run after
108
+ # digit collapsing to avoid interfering with numeric patterns.
109
+ - fix_ampm_letter_spacing
110
+ - remove_letter_spelling_markers
111
+ - remove_zero_minutes_from_time
112
+ - remove_trailing_dot_word_from_emails
113
+ - restore_unit_slash
114
+
115
+ # --- Phase 4: Final cleanup ---
116
+ - remove_trailing_period
117
+ # Final digit-collapse pass: late restores above (phone plus, unit slash)
118
+ # can produce new adjacent-digit sequences that need collapsing.
119
+ - remove_spaces_between_adjacent_digits # 3rd run: after late restores
@@ -0,0 +1,4 @@
1
+ from . import text, word
2
+ from .registry import get_step_registry
3
+
4
+ __all__ = ["text", "word", "get_step_registry"]
@@ -0,0 +1,6 @@
1
+ from .protect_step import ProtectStep
2
+ from .restore_step import RestoreStep
3
+ from .text_step import TextStep
4
+ from .word_step import WordStep
5
+
6
+ __all__ = ["TextStep", "WordStep", "ProtectStep", "RestoreStep"]
@@ -0,0 +1,24 @@
1
+ import re
2
+ from abc import abstractmethod
3
+
4
+ from normalization.constants.protectors import ProtectPlaceholder
5
+ from normalization.languages.base import LanguageOperators
6
+ from normalization.steps.base.text_step import TextStep
7
+
8
+
9
+ class ProtectStep(TextStep):
10
+ """
11
+ Protect characters with a placeholder.
12
+ How to implement :
13
+ - Define a class that inherits from ProtectStep.
14
+ - Define the placeholder attribute to the ProtectPlaceholder enum value that corresponds to the characters to protect.
15
+ - Implement the _pattern method to return a regular expression pattern that matches the characters to protect.
16
+ """
17
+
18
+ placeholder: ProtectPlaceholder
19
+
20
+ @abstractmethod
21
+ def _pattern(self, operators: LanguageOperators) -> re.Pattern: ...
22
+
23
+ def __call__(self, text: str, operators: LanguageOperators) -> str:
24
+ return self._pattern(operators).sub(rf"\1{self.placeholder.value}\2", text)
@@ -0,0 +1,23 @@
1
+ from abc import abstractmethod
2
+
3
+ from normalization.constants.protectors import ProtectPlaceholder
4
+ from normalization.languages.base import LanguageOperators
5
+ from normalization.steps.base.text_step import TextStep
6
+
7
+
8
+ class RestoreStep(TextStep):
9
+ """
10
+ Restore the protected placeholder.
11
+ """
12
+
13
+ placeholder: ProtectPlaceholder
14
+
15
+ @abstractmethod
16
+ def _replacement(self, operators: LanguageOperators) -> str: ...
17
+
18
+ def __call__(self, text: str, operators: LanguageOperators) -> str:
19
+ text = text.replace(self.placeholder.value, self._replacement(operators))
20
+ text = text.replace(
21
+ self.placeholder.value.lower(), self._replacement(operators)
22
+ )
23
+ return text
@@ -0,0 +1,11 @@
1
+ from typing import Protocol
2
+
3
+ from normalization.languages.base import LanguageOperators
4
+
5
+
6
+ class TextStep(Protocol):
7
+ """A transformation applied to the full text string."""
8
+
9
+ name: str
10
+
11
+ def __call__(self, text: str, operators: LanguageOperators) -> str: ...
@@ -0,0 +1,11 @@
1
+ from typing import Protocol
2
+
3
+ from normalization.languages.base import LanguageOperators
4
+
5
+
6
+ class WordStep(Protocol):
7
+ """A transformation applied to a single word token."""
8
+
9
+ name: str
10
+
11
+ def __call__(self, word: str, operators: LanguageOperators) -> str: ...
@@ -0,0 +1,26 @@
1
+ from typing import Type
2
+
3
+ from normalization.steps.base import TextStep, WordStep
4
+
5
+ _STEP_REGISTRY: dict[str, dict[str, Type[TextStep] | Type[WordStep]]] = {
6
+ "text": {},
7
+ "word": {},
8
+ }
9
+
10
+
11
+ def register_step(cls):
12
+ """Decorator that auto-registers a step class by its `name` attribute."""
13
+ assert hasattr(cls, "name"), f"{cls} must define a `name` class attribute"
14
+
15
+ # Determine step type based on module path
16
+ step_type = "text" if ".text." in cls.__module__ else "word"
17
+
18
+ assert cls.name not in _STEP_REGISTRY[step_type], (
19
+ f"Step name '{cls.name}' is already registered in {step_type}"
20
+ )
21
+ _STEP_REGISTRY[step_type][cls.name] = cls
22
+ return cls
23
+
24
+
25
+ def get_step_registry() -> dict[str, dict[str, Type[TextStep] | Type[WordStep]]]:
26
+ return _STEP_REGISTRY
@@ -0,0 +1,79 @@
1
+ from . import (
2
+ apply_sentence_level_replacements,
3
+ casefold_text,
4
+ convert_comparison_operators_to_words,
5
+ convert_decimal_periods_to_decimal_word,
6
+ convert_degree_symbols_to_words,
7
+ convert_digit_word_sequences_to_digits,
8
+ convert_dots_to_words_in_technical_contexts,
9
+ convert_oclock_to_numeric_time,
10
+ convert_roman_numerals_to_digits,
11
+ convert_word_based_time_patterns,
12
+ expand_alphanumeric_codes,
13
+ expand_contractions,
14
+ expand_written_numbers_to_digits,
15
+ expand_www_abbreviation,
16
+ fix_ampm_letter_spacing,
17
+ fix_dot_adjacent_number_words,
18
+ fix_one_word_in_numeric_contexts,
19
+ fix_version_number_v_prefix,
20
+ format_time_patterns_with_ampm,
21
+ normalize_numeric_time_formats,
22
+ normalize_punctuation_between_number_words,
23
+ placeholders,
24
+ protect_plus_word_before_digit_words,
25
+ remove_acronym_periods,
26
+ remove_diacritics,
27
+ remove_filler_words,
28
+ remove_hash_before_numbers,
29
+ remove_non_numeric_trailing_dots,
30
+ remove_spaces_between_adjacent_digits,
31
+ remove_standalone_currency_symbols,
32
+ remove_symbols,
33
+ remove_thousand_separators,
34
+ remove_trailing_apostrophe_space,
35
+ remove_trailing_dot_word_from_emails,
36
+ remove_trailing_period,
37
+ remove_zero_minutes_from_time,
38
+ replace_currency,
39
+ )
40
+
41
+ __all__ = [
42
+ "apply_sentence_level_replacements",
43
+ "casefold_text",
44
+ "convert_comparison_operators_to_words",
45
+ "convert_decimal_periods_to_decimal_word",
46
+ "convert_degree_symbols_to_words",
47
+ "convert_digit_word_sequences_to_digits",
48
+ "convert_dots_to_words_in_technical_contexts",
49
+ "convert_oclock_to_numeric_time",
50
+ "convert_roman_numerals_to_digits",
51
+ "convert_word_based_time_patterns",
52
+ "expand_alphanumeric_codes",
53
+ "expand_contractions",
54
+ "expand_www_abbreviation",
55
+ "expand_written_numbers_to_digits",
56
+ "fix_ampm_letter_spacing",
57
+ "fix_dot_adjacent_number_words",
58
+ "fix_one_word_in_numeric_contexts",
59
+ "fix_version_number_v_prefix",
60
+ "format_time_patterns_with_ampm",
61
+ "normalize_numeric_time_formats",
62
+ "normalize_punctuation_between_number_words",
63
+ "placeholders",
64
+ "protect_plus_word_before_digit_words",
65
+ "remove_diacritics",
66
+ "remove_filler_words",
67
+ "remove_hash_before_numbers",
68
+ "remove_acronym_periods",
69
+ "remove_non_numeric_trailing_dots",
70
+ "remove_spaces_between_adjacent_digits",
71
+ "remove_standalone_currency_symbols",
72
+ "remove_symbols",
73
+ "remove_thousand_separators",
74
+ "remove_trailing_apostrophe_space",
75
+ "remove_trailing_dot_word_from_emails",
76
+ "remove_trailing_period",
77
+ "remove_zero_minutes_from_time",
78
+ "replace_currency",
79
+ ]
@@ -0,0 +1,29 @@
1
+ import re
2
+
3
+ from normalization.languages.base import LanguageOperators
4
+ from normalization.steps.base import TextStep
5
+ from normalization.steps.registry import register_step
6
+
7
+
8
+ @register_step
9
+ class ApplySentenceLevelReplacementsStep(TextStep):
10
+ """Apply multi-word phrase replacements (e.g. 'good bye' -> 'goodbye').
11
+
12
+ Reads operators.config.sentence_replacements. Applies longest match first so that more specific phrases take priority over shorter overlapping ones.
13
+ No effect when the dict is empty.
14
+ """
15
+
16
+ name = "apply_sentence_level_replacements"
17
+
18
+ def __call__(self, text: str, operators: LanguageOperators) -> str:
19
+ replacements = operators.config.sentence_replacements
20
+ if replacements is None:
21
+ # TODO: warn or log when sentence_replacements is not configured for this language
22
+ return text
23
+ for pattern, replacement in sorted(
24
+ replacements.items(), key=lambda x: len(x[0]), reverse=True
25
+ ):
26
+ text = re.sub(
27
+ rf"\b{re.escape(pattern)}\b", replacement, text, flags=re.IGNORECASE
28
+ )
29
+ return text
@@ -0,0 +1,13 @@
1
+ from normalization.languages.base import LanguageOperators
2
+ from normalization.steps.base import TextStep
3
+ from normalization.steps.registry import register_step
4
+
5
+
6
+ @register_step
7
+ class CasefoldTextStep(TextStep):
8
+ """Lowercase all text using str.casefold()."""
9
+
10
+ name = "casefold_text"
11
+
12
+ def __call__(self, text: str, operators: LanguageOperators) -> str:
13
+ return text.casefold()