.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.plugins.calculator.SXNGPlugin Class Reference
Inheritance diagram for searx.plugins.calculator.SXNGPlugin:
Collaboration diagram for searx.plugins.calculator.SXNGPlugin:

Public Member Functions

None __init__ (self, "PluginCfg" plg_cfg)
 timeout_func (self, timeout, func, *args, **kwargs)
EngineResults post_search (self, "SXNG_Request" request, "SearchWithPlugins" search)
Public Member Functions inherited from searx.plugins._core.Plugin
None __init__ (self, "PluginCfg" plg_cfg)
int __hash__ (self)
 __eq__ (self, typing.Any other)
bool init (self, "flask.Flask" app)
bool pre_search (self, SXNG_Request request, "SearchWithPlugins" search)
bool on_result (self, SXNG_Request request, "SearchWithPlugins" search, Result result)

Public Attributes

 info

Additional Inherited Members

Static Public Attributes inherited from searx.plugins._core.Plugin
str id = ""
typing active .ClassVar[bool]
list keywords = []
logging log .Logger
str fqn = ""

Detailed Description

Plugin converts strings to different hash digests.  The results are
displayed in area for the "answers".

Definition at line 25 of file calculator.py.

Constructor & Destructor Documentation

◆ __init__()

None searx.plugins.calculator.SXNGPlugin.__init__ ( self,
"PluginCfg" plg_cfg )

Definition at line 32 of file calculator.py.

32 def __init__(self, plg_cfg: "PluginCfg") -> None:
33 super().__init__(plg_cfg)
34
35 self.info = PluginInfo(
36 id=self.id,
37 name=gettext("Basic Calculator"),
38 description=gettext("Calculate mathematical expressions via the search bar"),
39 preference_section="general",
40 )
41

References __init__().

Referenced by __init__().

Here is the call graph for this function:
Here is the caller graph for this function:

Member Function Documentation

◆ post_search()

EngineResults searx.plugins.calculator.SXNGPlugin.post_search ( self,
"SXNG_Request" request,
"SearchWithPlugins" search )
Runs AFTER the search request.  Can return a list of
:py:obj:`Result <searx.result_types._base.Result>` objects to be added to the
final result list.

Reimplemented from searx.plugins._core.Plugin.

Definition at line 58 of file calculator.py.

58 def post_search(self, request: "SXNG_Request", search: "SearchWithPlugins") -> EngineResults:
59 results = EngineResults()
60
61 # only show the result of the expression on the first page
62 if search.search_query.pageno > 1:
63 return results
64
65 query = search.search_query.query
66 # in order to avoid DoS attacks with long expressions, ignore long expressions
67 if len(query) > 100:
68 return results
69
70 # replace commonly used math operators with their proper Python operator
71 query = query.replace("x", "*").replace(":", "/")
72
73 # Is this a term that can be calculated?
74 word, constants = "", set()
75 for x in query:
76 # Alphabetic characters are defined as "Letters" in the Unicode
77 # character database and are the constants in an equation.
78 if x.isalpha():
79 word += x.strip()
80 elif word:
81 constants.add(word)
82 word = ""
83
84 # In the term of an arithmetic operation there should be no other
85 # alphabetic characters besides the constants
86 if constants - set(math_constants):
87 return results
88
89 # use UI language
90 ui_locale = babel.Locale.parse(request.preferences.get_value("locale"), sep="-")
91
92 # parse the number system in a localized way
93 def _decimal(match: re.Match) -> str:
94 val = match.string[match.start() : match.end()]
95 val = babel.numbers.parse_decimal(val, ui_locale, numbering_system="latn")
96 return str(val)
97
98 decimal = ui_locale.number_symbols["latn"]["decimal"]
99 group = ui_locale.number_symbols["latn"]["group"]
100 query = re.sub(f"[0-9]+[{decimal}|{group}][0-9]+[{decimal}|{group}]?[0-9]?", _decimal, query)
101
102 # in python, powers are calculated via **
103 query_py_formatted = query.replace("^", "**")
104
105 # Prevent the runtime from being longer than 50 ms
106 res = self.timeout_func(0.05, _eval_expr, query_py_formatted)
107 if res is None or res[0] == "":
108 return results
109
110 res, is_boolean = res
111 if is_boolean:
112 res = "True" if res != 0 else "False"
113 else:
114 res = babel.numbers.format_decimal(res, locale=ui_locale)
115 results.add(results.types.Answer(answer=f"{search.search_query.query} = {res}"))
116
117 return results
118
119

References timeout_func().

Here is the call graph for this function:

◆ timeout_func()

searx.plugins.calculator.SXNGPlugin.timeout_func ( self,
timeout,
func,
* args,
** kwargs )

Definition at line 42 of file calculator.py.

42 def timeout_func(self, timeout, func, *args, **kwargs):
43 que = mp_fork.Queue()
44 p = mp_fork.Process(target=handler, args=(que, func, args), kwargs=kwargs)
45 p.start()
46 p.join(timeout=timeout)
47 ret_val = None
48 # pylint: disable=used-before-assignment,undefined-variable
49 if not p.is_alive():
50 ret_val = que.get()
51 else:
52 self.log.debug("terminate function (%s: %s // %s) after timeout is exceeded", func.__name__, args, kwargs)
53 p.terminate()
54 p.join()
55 p.close()
56 return ret_val
57

References searx.plugins._core.Plugin.log.

Referenced by post_search().

Here is the caller graph for this function:

Member Data Documentation

◆ info

searx.plugins.calculator.SXNGPlugin.info
Initial value:
= PluginInfo(
id=self.id,
name=gettext("Basic Calculator"),
description=gettext("Calculate mathematical expressions via the search bar"),
preference_section="general",
)

Definition at line 35 of file calculator.py.


The documentation for this class was generated from the following file:
  • /home/andrew/Documents/code/public/searxng/searx/plugins/calculator.py