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 term = ' '.join(n.term_lookup for n in query.nodes[start + 1:end + 1])
197 query.add_token(qmod.TokenRange(start, end),
199 ICUToken(penalty=0.1, token=0, count=1, addr_count=1,
200 lookup_word=pc, word_token=term,
202 self.rerank_tokens(query)
204 log().table_dump('Word tokens', _dump_word_tokens(query))
208 def normalize_text(self, text: str) -> str:
209 """ Bring the given text into a normalized form. That is the
210 standardized form search will work with. All information removed
211 at this stage is inevitably lost.
213 return cast(str, self.normalizer.transliterate(text)).strip('-: ')
215 def split_query(self, query: qmod.QueryStruct) -> None:
216 """ Transliterate the phrases and split them into tokens.
218 for phrase in query.source:
219 query.nodes[-1].ptype = phrase.ptype
220 phrase_split = re.split('([ :-])', phrase.text)
221 # The zip construct will give us the pairs of word/break from
222 # the regular expression split. As the split array ends on the
223 # final word, we simply use the fillvalue to even out the list and
224 # add the phrase break at the end.
225 for word, breakchar in zip_longest(*[iter(phrase_split)]*2, fillvalue=','):
228 trans = self.transliterator.transliterate(word)
230 for term in trans.split(' '):
232 query.add_node(qmod.BREAK_TOKEN, phrase.ptype,
233 PENALTY_IN_TOKEN_BREAK[qmod.BREAK_TOKEN],
235 query.nodes[-1].adjust_break(breakchar,
236 PENALTY_IN_TOKEN_BREAK[breakchar])
238 query.nodes[-1].adjust_break(qmod.BREAK_END, PENALTY_IN_TOKEN_BREAK[qmod.BREAK_END])
240 async def lookup_in_db(self, words: List[str]) -> 'sa.Result[Any]':
241 """ Return the token information from the database for the
244 This function excludes postcode tokens
246 t = self.conn.t.meta.tables['word']
247 return await self.conn.execute(t.select()
248 .where(t.c.word_token.in_(words))
249 .where(t.c.type != 'P'))
251 def add_extra_tokens(self, query: qmod.QueryStruct) -> None:
252 """ Add tokens to query that are not saved in the database.
255 for i, node in enumerate(query.nodes):
256 is_full_token = node.btype not in (qmod.BREAK_TOKEN, qmod.BREAK_PART)
257 if need_hnr and is_full_token \
258 and len(node.term_normalized) <= 4 and node.term_normalized.isdigit():
259 query.add_token(qmod.TokenRange(i-1, i), qmod.TOKEN_HOUSENUMBER,
260 ICUToken(penalty=0.5, token=0,
261 count=1, addr_count=1,
262 lookup_word=node.term_lookup,
263 word_token=node.term_lookup, info=None))
265 need_hnr = is_full_token and not node.has_tokens(i+1, qmod.TOKEN_HOUSENUMBER)
267 def rerank_tokens(self, query: qmod.QueryStruct) -> None:
268 """ Add penalties to tokens that depend on presence of other token.
270 for i, node, tlist in query.iter_token_lists():
271 if tlist.ttype == qmod.TOKEN_POSTCODE:
272 tlen = len(cast(ICUToken, tlist.tokens[0]).word_token)
273 for repl in node.starting:
274 if repl.end == tlist.end and repl.ttype != qmod.TOKEN_POSTCODE \
275 and (repl.ttype != qmod.TOKEN_HOUSENUMBER or tlen > 4):
276 repl.add_penalty(0.39)
277 elif (tlist.ttype == qmod.TOKEN_HOUSENUMBER
278 and len(tlist.tokens[0].lookup_word) <= 3):
279 if any(c.isdigit() for c in tlist.tokens[0].lookup_word):
280 for repl in node.starting:
281 if repl.end == tlist.end and repl.ttype != qmod.TOKEN_HOUSENUMBER:
282 repl.add_penalty(0.5 - tlist.tokens[0].penalty)
283 elif tlist.ttype not in (qmod.TOKEN_COUNTRY, qmod.TOKEN_PARTIAL):
284 norm = ' '.join(n.term_normalized for n in query.nodes[i + 1:tlist.end + 1]
285 if n.btype != qmod.BREAK_TOKEN)
287 # Can happen when the token only covers a partial term
288 norm = query.nodes[i + 1].term_normalized
289 for token in tlist.tokens:
290 cast(ICUToken, token).rematch(norm)
293 def _dump_word_tokens(query: qmod.QueryStruct) -> Iterator[List[Any]]:
294 yield ['type', 'from', 'to', 'token', 'word_token', 'lookup_word', 'penalty', 'count', 'info']
295 for i, node in enumerate(query.nodes):
296 for tlist in node.starting:
297 for token in tlist.tokens:
298 t = cast(ICUToken, token)
299 yield [tlist.ttype, str(i), str(tlist.end), t.token, t.word_token or '',
300 t.lookup_word or '', t.penalty, t.count, t.info]
303 async def create_query_analyzer(conn: SearchConnection) -> AbstractQueryAnalyzer:
304 """ Create and set up a new query analyzer for a database based
305 on the ICU tokenizer.
307 async def _get_config() -> ICUAnalyzerConfig:
308 if 'word' not in conn.t.meta.tables:
309 sa.Table('word', conn.t.meta,
310 sa.Column('word_id', sa.Integer),
311 sa.Column('word_token', sa.Text, nullable=False),
312 sa.Column('type', sa.Text, nullable=False),
313 sa.Column('word', sa.Text),
314 sa.Column('info', Json))
316 return await ICUAnalyzerConfig.create(conn)
318 config = await conn.get_cached_value('ICUTOK', 'config', _get_config)
320 return ICUQueryAnalyzer(conn, config)