1 # SPDX-License-Identifier: GPL-2.0-only
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2022 by the Nominatim developer community.
 
   6 # For a full list of authors see the git log.
 
   8 Abstract class defintions for tokenizers. These base classes are here
 
   9 mainly for documentation purposes.
 
  11 from abc import ABC, abstractmethod
 
  12 from typing import List, Tuple, Dict, Any
 
  14 from nominatim.config import Configuration
 
  15 from nominatim.indexer.place_info import PlaceInfo
 
  17 # pylint: disable=unnecessary-pass
 
  19 class AbstractAnalyzer(ABC):
 
  20     """ The analyzer provides the functions for analysing names and building
 
  23         Analyzers are instantiated on a per-thread base. Access to global data
 
  24         structures must be synchronised accordingly.
 
  27     def __enter__(self) -> 'AbstractAnalyzer':
 
  31     def __exit__(self, exc_type, exc_value, traceback) -> None:
 
  36     def close(self) -> None:
 
  37         """ Free all resources used by the analyzer.
 
  42     def get_word_token_info(self, words: List[str]) -> List[Tuple[str, str, int]]:
 
  43         """ Return token information for the given list of words.
 
  45             The function is used for testing and debugging only
 
  46             and does not need to be particularly efficient.
 
  49                 words: A list of words to look up the tokens for.
 
  50                        If a word starts with # it is assumed to be a full name
 
  51                        otherwise is a partial term.
 
  54                 The function returns the list of all tuples that could be
 
  55                 found for the given words. Each list entry is a tuple of
 
  56                 (original word, word token, word id).
 
  61     def normalize_postcode(self, postcode: str) -> str:
 
  62         """ Convert the postcode to its standardized form.
 
  64             This function must yield exactly the same result as the SQL function
 
  65             `token_normalized_postcode()`.
 
  68                 postcode: The postcode to be normalized.
 
  71                 The given postcode after normalization.
 
  76     def update_postcodes_from_db(self) -> None:
 
  77         """ Update the tokenizer's postcode tokens from the current content
 
  78             of the `location_postcode` table.
 
  83     def update_special_phrases(self, phrases: List[Tuple[str, str, str, str]],
 
  84                                should_replace: bool) -> None:
 
  85         """ Update the tokenizer's special phrase tokens from the given
 
  86             list of special phrases.
 
  89                 phrases: The new list of special phrases. Each entry is
 
  90                          a tuple of (phrase, class, type, operator).
 
  91                 should_replace: If true, replace the current list of phrases.
 
  92                                 When false, just add the given phrases to the
 
  93                                 ones that already exist.
 
  98     def add_country_names(self, country_code: str, names: Dict[str, str]):
 
  99         """ Add the given names to the tokenizer's list of country tokens.
 
 102                 country_code: two-letter country code for the country the names
 
 104                 names: Dictionary of name type to name.
 
 109     def process_place(self, place: PlaceInfo) -> Any:
 
 110         """ Extract tokens for the given place and compute the
 
 111             information to be handed to the PL/pgSQL processor for building
 
 115                 place: Place information retrived from the database.
 
 118                 A JSON-serialisable structure that will be handed into
 
 119                 the database via the `token_info` field.
 
 124 class AbstractTokenizer(ABC):
 
 125     """ The tokenizer instance is the central instance of the tokenizer in
 
 126         the system. There will only be a single instance of the tokenizer
 
 131     def init_new_db(self, config: Configuration, init_db: bool = True) -> None:
 
 132         """ Set up a new tokenizer for the database.
 
 134             The function should copy all necessary data into the project
 
 135             directory or save it in the property table to make sure that
 
 136             the tokenizer remains stable over updates.
 
 139               config: Read-only object with configuration options.
 
 141               init_db: When set to False, then initialisation of database
 
 142                 tables should be skipped. This option is only required for
 
 143                 migration purposes and can be savely ignored by custom
 
 146             TODO: can we move the init_db parameter somewhere else?
 
 151     def init_from_project(self, config: Configuration) -> None:
 
 152         """ Initialise the tokenizer from an existing database setup.
 
 154             The function should load all previously saved configuration from
 
 155             the project directory and/or the property table.
 
 158               config: Read-only object with configuration options.
 
 163     def finalize_import(self, config: Configuration) -> None:
 
 164         """ This function is called at the very end of an import when all
 
 165             data has been imported and indexed. The tokenizer may create
 
 166             at this point any additional indexes and data structures needed
 
 170               config: Read-only object with configuration options.
 
 175     def update_sql_functions(self, config: Configuration) -> None:
 
 176         """ Update the SQL part of the tokenizer. This function is called
 
 177             automatically on migrations or may be called explicitly by the
 
 178             user through the `nominatim refresh --functions` command.
 
 180             The tokenizer must only update the code of the tokenizer. The
 
 181             data structures or data itself must not be changed by this function.
 
 184               config: Read-only object with configuration options.
 
 189     def check_database(self, config: Configuration) -> str:
 
 190         """ Check that the database is set up correctly and ready for being
 
 194               config: Read-only object with configuration options.
 
 197               If an issue was found, return an error message with the
 
 198               description of the issue as well as hints for the user on
 
 199               how to resolve the issue. If everything is okay, return `None`.
 
 204     def update_statistics(self) -> None:
 
 205         """ Recompute any tokenizer statistics necessary for efficient lookup.
 
 206             This function is meant to be called from time to time by the user
 
 207             to improve performance. However, the tokenizer must not depend on
 
 208             it to be called in order to work.
 
 213     def update_word_tokens(self) -> None:
 
 214         """ Do house-keeping on the tokenizers internal data structures.
 
 215             Remove unused word tokens, resort data etc.
 
 220     def name_analyzer(self) -> AbstractAnalyzer:
 
 221         """ Create a new analyzer for tokenizing names and queries
 
 222             using this tokinzer. Analyzers are context managers and should
 
 226             with tokenizer.name_analyzer() as analyzer:
 
 230             When used outside the with construct, the caller must ensure to
 
 231             call the close() function before destructing the analyzer.