.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
unit_converter.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""A plugin for converting measured values from one unit to another unit (a
3unit converter).
4
5The plugin looks up the symbols (given in the query term) in a list of
6converters, each converter is one item in the list (compare
7:py:obj:`ADDITIONAL_UNITS`). If the symbols are ambiguous, the matching units
8of measurement are evaluated. The weighting in the evaluation results from the
9sorting of the :py:obj:`list of unit converters<symbol_to_si>`.
10"""
11from __future__ import annotations
12import typing
13import re
14import babel.numbers
15
16from flask_babel import gettext, get_locale
17
18from searx.wikidata_units import symbol_to_si
19from searx.plugins import Plugin, PluginInfo
20from searx.result_types import EngineResults
21
22if typing.TYPE_CHECKING:
23 from searx.search import SearchWithPlugins
24 from searx.extended_types import SXNG_Request
25 from searx.plugins import PluginCfg
26
27
28name = ""
29description = gettext("")
30
31plugin_id = ""
32preference_section = ""
33
34CONVERT_KEYWORDS = ["in", "to", "as"]
35
36
38 """Convert between units. The result is displayed in area for the
39 "answers".
40 """
41
42 id = "unit_converter"
43
44 def __init__(self, plg_cfg: "PluginCfg") -> None:
45 super().__init__(plg_cfg)
46
48 id=self.id,
49 name=gettext("Unit converter plugin"),
50 description=gettext("Convert between units"),
51 preference_section="general",
52 )
53
54 def post_search(self, request: "SXNG_Request", search: "SearchWithPlugins") -> EngineResults:
55 results = EngineResults()
56
57 # only convert between units on the first page
58 if search.search_query.pageno > 1:
59 return results
60
61 query = search.search_query.query
62 query_parts = query.split(" ")
63
64 if len(query_parts) < 3:
65 return results
66
67 for query_part in query_parts:
68 for keyword in CONVERT_KEYWORDS:
69 if query_part == keyword:
70 from_query, to_query = query.split(keyword, 1)
71 target_val = _parse_text_and_convert(from_query.strip(), to_query.strip())
72 if target_val:
73 results.add(results.types.Answer(answer=target_val))
74
75 return results
76
77
78# inspired from https://stackoverflow.com/a/42475086
79RE_MEASURE = r'''
80(?P<sign>[-+]?) # +/- or nothing for positive
81(\s*) # separator: white space or nothing
82(?P<number>[\d\.,]*) # number: 1,000.00 (en) or 1.000,00 (de)
83(?P<E>[eE][-+]?\d+)? # scientific notation: e(+/-)2 (*10^2)
84(\s*) # separator: white space or nothing
85(?P<unit>\S+) # unit of measure
86'''
87
88
89def _parse_text_and_convert(from_query, to_query) -> str | None:
90
91 # pylint: disable=too-many-branches, too-many-locals
92
93 if not (from_query and to_query):
94 return None
95
96 measured = re.match(RE_MEASURE, from_query, re.VERBOSE)
97 if not (measured and measured.group('number'), measured.group('unit')):
98 return None
99
100 # Symbols are not unique, if there are several hits for the from-unit, then
101 # the correct one must be determined by comparing it with the to-unit
102 # https://github.com/searxng/searxng/pull/3378#issuecomment-2080974863
103
104 # first: collecting possible units
105
106 source_list, target_list = [], []
107
108 for symbol, si_name, from_si, to_si, orig_symbol in symbol_to_si():
109
110 if symbol == measured.group('unit'):
111 source_list.append((si_name, to_si))
112 if symbol == to_query:
113 target_list.append((si_name, from_si, orig_symbol))
114
115 if not (source_list and target_list):
116 return None
117
118 source_to_si = target_from_si = target_symbol = None
119
120 # second: find the right unit by comparing list of from-units with list of to-units
121
122 for source in source_list:
123 for target in target_list:
124 if source[0] == target[0]: # compare si_name
125 source_to_si = source[1]
126 target_from_si = target[1]
127 target_symbol = target[2]
128
129 if not (source_to_si and target_from_si):
130 return None
131
132 _locale = get_locale() or 'en_US'
133
134 value = measured.group('sign') + measured.group('number') + (measured.group('E') or '')
135 value = babel.numbers.parse_decimal(value, locale=_locale)
136
137 # convert value to SI unit
138
139 if isinstance(source_to_si, (float, int)):
140 value = float(value) * source_to_si
141 else:
142 value = source_to_si(float(value))
143
144 # convert value from SI unit to target unit
145
146 if isinstance(target_from_si, (float, int)):
147 value = float(value) * target_from_si
148 else:
149 value = target_from_si(float(value))
150
151 if measured.group('E'):
152 # when incoming notation is scientific, outgoing notation is scientific
153 result = babel.numbers.format_scientific(value, locale=_locale)
154 else:
155 result = babel.numbers.format_decimal(value, locale=_locale, format='#,##0.##########;-#')
156
157 return f'{result} {target_symbol}'
EngineResults post_search(self, "SXNG_Request" request, "SearchWithPlugins" search)
None __init__(self, "PluginCfg" plg_cfg)
str|None _parse_text_and_convert(from_query, to_query)