1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2024 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Implementation of query analysis for the ICU tokenizer.
10 from typing import Tuple, Dict, List, Optional, Iterator, Any, cast
14 from itertools import zip_longest
16 from icu import Transliterator
18 import sqlalchemy as sa
20 from ..errors import UsageError
21 from ..typing import SaRow
22 from ..sql.sqlalchemy_types import Json
23 from ..connection import SearchConnection
24 from ..logging import log
25 from . import query as qmod
26 from ..query_preprocessing.config import QueryConfig
27 from ..query_preprocessing.base import QueryProcessingFunc
28 from .query_analyzer_factory import AbstractQueryAnalyzer
29 from .postcode_parser import PostcodeParser
34 'w': qmod.TOKEN_PARTIAL,
35 'H': qmod.TOKEN_HOUSENUMBER,
36 'P': qmod.TOKEN_POSTCODE,
37 'C': qmod.TOKEN_COUNTRY
40 PENALTY_IN_TOKEN_BREAK = {
41 qmod.BREAK_START: 0.5,
43 qmod.BREAK_PHRASE: 0.5,
44 qmod.BREAK_SOFT_PHRASE: 0.5,
51 @dataclasses.dataclass
52 class ICUToken(qmod.Token):
53 """ Specialised token for ICU tokenizer.
56 info: Optional[Dict[str, Any]]
58 def get_category(self) -> Tuple[str, str]:
60 return self.info.get('class', ''), self.info.get('type', '')
62 def rematch(self, norm: str) -> None:
63 """ Check how well the token matches the given normalized string
64 and add a penalty, if necessary.
66 if not self.lookup_word:
69 seq = difflib.SequenceMatcher(a=self.lookup_word, b=norm)
71 for tag, afrom, ato, bfrom, bto in seq.get_opcodes():
72 if tag in ('delete', 'insert') and (afrom == 0 or ato == len(self.lookup_word)):
74 elif tag == 'replace':
75 distance += max((ato-afrom), (bto-bfrom))
77 distance += abs((ato-afrom) - (bto-bfrom))
78 self.penalty += (distance/len(self.lookup_word))
81 def from_db_row(row: SaRow, base_penalty: float = 0.0) -> 'ICUToken':
82 """ Create a ICUToken from the row of the word table.
84 count = 1 if row.info is None else row.info.get('count', 1)
85 addr_count = 1 if row.info is None else row.info.get('addr_count', 1)
87 penalty = base_penalty
91 if len(row.word_token) == 1 and row.word_token == row.word:
92 penalty += 0.2 if row.word.isdigit() else 0.3
94 penalty += sum(0.1 for c in row.word_token if c != ' ' and not c.isdigit())
95 if all(not c.isdigit() for c in row.word_token):
96 penalty += 0.2 * (len(row.word_token) - 1)
98 if len(row.word_token) == 1:
102 lookup_word = row.word
104 lookup_word = row.info.get('lookup', row.word)
106 lookup_word = lookup_word.split('@', 1)[0]
108 lookup_word = row.word_token
110 return ICUToken(penalty=penalty, token=row.word_id, count=max(1, count),
111 lookup_word=lookup_word,
112 word_token=row.word_token, info=row.info,
113 addr_count=max(1, addr_count))
116 @dataclasses.dataclass
117 class ICUAnalyzerConfig:
118 postcode_parser: PostcodeParser
119 normalizer: Transliterator
120 transliterator: Transliterator
121 preprocessors: List[QueryProcessingFunc]
124 async def create(conn: SearchConnection) -> 'ICUAnalyzerConfig':
125 rules = await conn.get_property('tokenizer_import_normalisation')
126 normalizer = Transliterator.createFromRules("normalization", rules)
128 rules = await conn.get_property('tokenizer_import_transliteration')
129 transliterator = Transliterator.createFromRules("transliteration", rules)
131 preprocessing_rules = conn.config.load_sub_configuration('icu_tokenizer.yaml',
132 config='TOKENIZER_CONFIG')\
133 .get('query-preprocessing', [])
135 preprocessors: List[QueryProcessingFunc] = []
136 for func in preprocessing_rules:
137 if 'step' not in func:
138 raise UsageError("Preprocessing rule is missing the 'step' attribute.")
139 if not isinstance(func['step'], str):
140 raise UsageError("'step' attribute must be a simple string.")
142 module = conn.config.load_plugin_module(
143 func['step'], 'nominatim_api.query_preprocessing')
144 preprocessors.append(
145 module.create(QueryConfig(func).set_normalizer(normalizer)))
147 return ICUAnalyzerConfig(PostcodeParser(conn.config),
148 normalizer, transliterator, preprocessors)
151 class ICUQueryAnalyzer(AbstractQueryAnalyzer):
152 """ Converter for query strings into a tokenized query
153 using the tokens created by a ICU tokenizer.
155 def __init__(self, conn: SearchConnection, config: ICUAnalyzerConfig) -> None:
157 self.postcode_parser = config.postcode_parser
158 self.normalizer = config.normalizer
159 self.transliterator = config.transliterator
160 self.preprocessors = config.preprocessors
162 async def analyze_query(self, phrases: List[qmod.Phrase]) -> qmod.QueryStruct:
163 """ Analyze the given list of phrases and return the
166 log().section('Analyze query (using ICU tokenizer)')
167 for func in self.preprocessors:
168 phrases = func(phrases)
169 query = qmod.QueryStruct(phrases)
171 log().var_dump('Normalized query', query.source)
175 self.split_query(query)
176 log().var_dump('Transliterated query', lambda: query.get_transliterated_query())
177 words = query.extract_words(base_penalty=PENALTY_IN_TOKEN_BREAK[qmod.BREAK_WORD])
179 for row in await self.lookup_in_db(list(words.keys())):
180 for trange in words[row.word_token]:
181 token = ICUToken.from_db_row(row, trange.penalty or 0.0)
183 if row.info['op'] in ('in', 'near'):
184 if trange.start == 0:
185 query.add_token(trange, qmod.TOKEN_NEAR_ITEM, token)
187 if trange.start == 0 and trange.end == query.num_token_slots():
188 query.add_token(trange, qmod.TOKEN_NEAR_ITEM, token)
190 query.add_token(trange, qmod.TOKEN_QUALIFIER, token)
192 query.add_token(trange, DB_TO_TOKEN_TYPE[row.type], token)
194 self.add_extra_tokens(query)
195 for start, end, pc in self.postcode_parser.parse(query):
196 query.add_token(qmod.TokenRange(start, end),
198 ICUToken(penalty=0.1, token=0, count=1, addr_count=1,
199 lookup_word=pc, word_token=pc, info=None))
200 self.rerank_tokens(query)
202 log().table_dump('Word tokens', _dump_word_tokens(query))
206 def normalize_text(self, text: str) -> str:
207 """ Bring the given text into a normalized form. That is the
208 standardized form search will work with. All information removed
209 at this stage is inevitably lost.
211 return cast(str, self.normalizer.transliterate(text)).strip('-: ')
213 def split_query(self, query: qmod.QueryStruct) -> None:
214 """ Transliterate the phrases and split them into tokens.
216 for phrase in query.source:
217 query.nodes[-1].ptype = phrase.ptype
218 phrase_split = re.split('([ :-])', phrase.text)
219 # The zip construct will give us the pairs of word/break from
220 # the regular expression split. As the split array ends on the
221 # final word, we simply use the fillvalue to even out the list and
222 # add the phrase break at the end.
223 for word, breakchar in zip_longest(*[iter(phrase_split)]*2, fillvalue=','):
226 trans = self.transliterator.transliterate(word)
228 for term in trans.split(' '):
230 query.add_node(qmod.BREAK_TOKEN, phrase.ptype,
231 PENALTY_IN_TOKEN_BREAK[qmod.BREAK_TOKEN],
233 query.nodes[-1].adjust_break(breakchar,
234 PENALTY_IN_TOKEN_BREAK[breakchar])
236 query.nodes[-1].adjust_break(qmod.BREAK_END, PENALTY_IN_TOKEN_BREAK[qmod.BREAK_END])
238 async def lookup_in_db(self, words: List[str]) -> 'sa.Result[Any]':
239 """ Return the token information from the database for the
242 This function excludes postcode tokens
244 t = self.conn.t.meta.tables['word']
245 return await self.conn.execute(t.select()
246 .where(t.c.word_token.in_(words))
247 .where(t.c.type != 'P'))
249 def add_extra_tokens(self, query: qmod.QueryStruct) -> None:
250 """ Add tokens to query that are not saved in the database.
253 for i, node in enumerate(query.nodes):
254 is_full_token = node.btype not in (qmod.BREAK_TOKEN, qmod.BREAK_PART)
255 if need_hnr and is_full_token \
256 and len(node.term_normalized) <= 4 and node.term_normalized.isdigit():
257 query.add_token(qmod.TokenRange(i-1, i), qmod.TOKEN_HOUSENUMBER,
258 ICUToken(penalty=0.5, token=0,
259 count=1, addr_count=1,
260 lookup_word=node.term_lookup,
261 word_token=node.term_lookup, info=None))
263 need_hnr = is_full_token and not node.has_tokens(i+1, qmod.TOKEN_HOUSENUMBER)
265 def rerank_tokens(self, query: qmod.QueryStruct) -> None:
266 """ Add penalties to tokens that depend on presence of other token.
268 for i, node, tlist in query.iter_token_lists():
269 if tlist.ttype == qmod.TOKEN_POSTCODE:
270 for repl in node.starting:
271 if repl.end == tlist.end and repl.ttype != qmod.TOKEN_POSTCODE \
272 and (repl.ttype != qmod.TOKEN_HOUSENUMBER
273 or len(tlist.tokens[0].lookup_word) > 4):
274 repl.add_penalty(0.39)
275 elif (tlist.ttype == qmod.TOKEN_HOUSENUMBER
276 and len(tlist.tokens[0].lookup_word) <= 3):
277 if any(c.isdigit() for c in tlist.tokens[0].lookup_word):
278 for repl in node.starting:
279 if repl.end == tlist.end and repl.ttype != qmod.TOKEN_HOUSENUMBER:
280 repl.add_penalty(0.5 - tlist.tokens[0].penalty)
281 elif tlist.ttype not in (qmod.TOKEN_COUNTRY, qmod.TOKEN_PARTIAL):
282 norm = ' '.join(n.term_normalized for n in query.nodes[i + 1:tlist.end + 1]
283 if n.btype != qmod.BREAK_TOKEN)
285 # Can happen when the token only covers a partial term
286 norm = query.nodes[i + 1].term_normalized
287 for token in tlist.tokens:
288 cast(ICUToken, token).rematch(norm)
291 def _dump_word_tokens(query: qmod.QueryStruct) -> Iterator[List[Any]]:
292 yield ['type', 'from', 'to', 'token', 'word_token', 'lookup_word', 'penalty', 'count', 'info']
293 for i, node in enumerate(query.nodes):
294 for tlist in node.starting:
295 for token in tlist.tokens:
296 t = cast(ICUToken, token)
297 yield [tlist.ttype, str(i), str(tlist.end), t.token, t.word_token or '',
298 t.lookup_word or '', t.penalty, t.count, t.info]
301 async def create_query_analyzer(conn: SearchConnection) -> AbstractQueryAnalyzer:
302 """ Create and set up a new query analyzer for a database based
303 on the ICU tokenizer.
305 async def _get_config() -> ICUAnalyzerConfig:
306 if 'word' not in conn.t.meta.tables:
307 sa.Table('word', conn.t.meta,
308 sa.Column('word_id', sa.Integer),
309 sa.Column('word_token', sa.Text, nullable=False),
310 sa.Column('type', sa.Text, nullable=False),
311 sa.Column('word', sa.Text),
312 sa.Column('info', Json))
314 return await ICUAnalyzerConfig.create(conn)
316 config = await conn.get_cached_value('ICUTOK', 'config', _get_config)
318 return ICUQueryAnalyzer(conn, config)