.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
statistics.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2# pylint: disable=missing-module-docstring
3from __future__ import annotations
4
5from functools import reduce
6from operator import mul
7
8import babel
9import babel.numbers
10from flask_babel import gettext
11
12from searx.extended_types import sxng_request
13from searx.result_types import Answer
14from searx.result_types.answer import BaseAnswer
15
16from . import Answerer, AnswererInfo
17
18kw2func = [
19 ("min", min),
20 ("max", max),
21 ("avg", lambda args: sum(args) / len(args)),
22 ("sum", sum),
23 ("prod", lambda args: reduce(mul, args, 1)),
24 ("range", lambda args: max(args) - min(args)),
25]
26
27
29 """Statistics functions"""
30
31 keywords = [kw for kw, _ in kw2func]
32
33 def info(self):
34
35 return AnswererInfo(
36 name=gettext(self.__doc__),
37 description=gettext("Compute {func} of the arguments".format(func='/'.join(self.keywords))),
38 keywords=self.keywords,
39 examples=["avg 123 548 2.04 24.2"],
40 )
41
42 def answer(self, query: str) -> list[BaseAnswer]:
43
44 results = []
45 parts = query.split()
46 if len(parts) < 2:
47 return results
48
49 ui_locale = babel.Locale.parse(sxng_request.preferences.get_value('locale'), sep='-')
50
51 try:
52 args = [babel.numbers.parse_decimal(num, ui_locale, numbering_system="latn") for num in parts[1:]]
53 except: # pylint: disable=bare-except
54 # seems one of the args is not a float type, can't be converted to float
55 return results
56
57 for k, func in kw2func:
58 if k == parts[0]:
59 res = func(args)
60 res = babel.numbers.format_decimal(res, locale=ui_locale)
61 f_str = ', '.join(babel.numbers.format_decimal(arg, locale=ui_locale) for arg in args)
62 results.append(Answer(answer=f"[{ui_locale}] {k}({f_str}) = {res} "))
63 break
64
65 return results
list[BaseAnswer] answer(self, str query)
Definition statistics.py:42