]> git.openstreetmap.org Git - nominatim.git/blob - src/nominatim_api/query_preprocessing/regex_replace.py
Merge pull request #3686 from astridx/output_names
[nominatim.git] / src / nominatim_api / query_preprocessing / regex_replace.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 This preprocessor replaces values in a given input based on pre-defined regex rules.
9
10 Arguments:
11     pattern: Regex pattern to be applied on the input
12     replace: The string that it is to be replaced with
13 """
14 from typing import List
15 import re
16
17 from .config import QueryConfig
18 from .base import QueryProcessingFunc
19 from ..search.query import Phrase
20
21
22 class _GenericPreprocessing:
23     """Perform replacements to input phrases using custom regex patterns."""
24
25     def __init__(self, config: QueryConfig) -> None:
26         """Initialise the _GenericPreprocessing class with patterns from the ICU config file."""
27         self.config = config
28
29         match_patterns = self.config.get('replacements', 'Key not found')
30         self.compiled_patterns = [
31             (re.compile(item['pattern']), item['replace']) for item in match_patterns
32             ]
33
34     def split_phrase(self, phrase: Phrase) -> Phrase:
35         """This function performs replacements on the given text using regex patterns."""
36         for item in self.compiled_patterns:
37             phrase.text = item[0].sub(item[1], phrase.text)
38
39         return phrase
40
41     def __call__(self, phrases: List[Phrase]) -> List[Phrase]:
42         """
43         Return the final Phrase list.
44         Returns an empty list if there is nothing left after split_phrase.
45         """
46         result = [p for p in map(self.split_phrase, phrases) if p.text.strip()]
47         return result
48
49
50 def create(config: QueryConfig) -> QueryProcessingFunc:
51     """ Create a function for generic preprocessing."""
52     return _GenericPreprocessing(config)