.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]
25
26
28 """Statistics functions"""
29
30 keywords = [kw for kw, _ in kw2func]
31
32 def info(self):
33
34 return AnswererInfo(
35 name=gettext(self.__doc__),
36 description=gettext("Compute {func} of the arguments".format(func='/'.join(self.keywords))),
37 keywords=self.keywords,
38 examples=["avg 123 548 2.04 24.2"],
39 )
40
41 def answer(self, query: str) -> list[BaseAnswer]:
42
43 results = []
44 parts = query.split()
45 if len(parts) < 2:
46 return results
47
48 ui_locale = babel.Locale.parse(sxng_request.preferences.get_value('locale'), sep='-')
49
50 try:
51 args = [babel.numbers.parse_decimal(num, ui_locale, numbering_system="latn") for num in parts[1:]]
52 except: # pylint: disable=bare-except
53 # seems one of the args is not a float type, can't be converted to float
54 return results
55
56 for k, func in kw2func:
57 if k == parts[0]:
58 res = func(args)
59 res = babel.numbers.format_decimal(res, locale=ui_locale)
60 f_str = ', '.join(babel.numbers.format_decimal(arg, locale=ui_locale) for arg in args)
61 results.append(Answer(answer=f"[{ui_locale}] {k}({f_str}) = {res} "))
62 break
63
64 return results
list[BaseAnswer] answer(self, str query)
Definition statistics.py:41