.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
calculator.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Calculate mathematical expressions using :py:obj`ast.parse` (mode="eval").
3"""
4
5from __future__ import annotations
6from typing import Callable
7
8import ast
9import re
10import operator
11import multiprocessing
12
13import babel
14import babel.numbers
15from flask_babel import gettext
16
17from searx.result_types import EngineResults
18
19name = "Basic Calculator"
20description = gettext("Calculate mathematical expressions via the search bar")
21default_on = True
22preference_section = 'general'
23plugin_id = 'calculator'
24
25operators: dict[type, Callable] = {
26 ast.Add: operator.add,
27 ast.Sub: operator.sub,
28 ast.Mult: operator.mul,
29 ast.Div: operator.truediv,
30 ast.Pow: operator.pow,
31 ast.BitXor: operator.xor,
32 ast.USub: operator.neg,
33}
34
35# with multiprocessing.get_context("fork") we are ready for Py3.14 (by emulating
36# the old behavior "fork") but it will not solve the core problem of fork, nor
37# will it remove the deprecation warnings in py3.12 & py3.13. Issue is
38# ddiscussed here: https://github.com/searxng/searxng/issues/4159
39mp_fork = multiprocessing.get_context("fork")
40
41
42def _eval_expr(expr):
43 """
44 >>> _eval_expr('2^6')
45 64
46 >>> _eval_expr('2**6')
47 64
48 >>> _eval_expr('1 + 2*3**(4^5) / (6 + -7)')
49 -5.0
50 """
51 try:
52 return _eval(ast.parse(expr, mode='eval').body)
53 except ZeroDivisionError:
54 # This is undefined
55 return ""
56
57
58def _eval(node):
59 if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
60 return node.value
61
62 if isinstance(node, ast.BinOp):
63 return operators[type(node.op)](_eval(node.left), _eval(node.right))
64
65 if isinstance(node, ast.UnaryOp):
66 return operators[type(node.op)](_eval(node.operand))
67
68 raise TypeError(node)
69
70
71def handler(q: multiprocessing.Queue, func, args, **kwargs): # pylint:disable=invalid-name
72 try:
73 q.put(func(*args, **kwargs))
74 except:
75 q.put(None)
76 raise
77
78
79def timeout_func(timeout, func, *args, **kwargs):
80
81 que = mp_fork.Queue()
82 p = mp_fork.Process(target=handler, args=(que, func, args), kwargs=kwargs)
83 p.start()
84 p.join(timeout=timeout)
85 ret_val = None
86 # pylint: disable=used-before-assignment,undefined-variable
87 if not p.is_alive():
88 ret_val = que.get()
89 else:
90 logger.debug("terminate function after timeout is exceeded") # type: ignore
91 p.terminate()
92 p.join()
93 p.close()
94 return ret_val
95
96
97def post_search(request, search) -> EngineResults:
98 results = EngineResults()
99
100 # only show the result of the expression on the first page
101 if search.search_query.pageno > 1:
102 return results
103
104 query = search.search_query.query
105 # in order to avoid DoS attacks with long expressions, ignore long expressions
106 if len(query) > 100:
107 return results
108
109 # replace commonly used math operators with their proper Python operator
110 query = query.replace("x", "*").replace(":", "/")
111
112 # use UI language
113 ui_locale = babel.Locale.parse(request.preferences.get_value('locale'), sep='-')
114
115 # parse the number system in a localized way
116 def _decimal(match: re.Match) -> str:
117 val = match.string[match.start() : match.end()]
118 val = babel.numbers.parse_decimal(val, ui_locale, numbering_system="latn")
119 return str(val)
120
121 decimal = ui_locale.number_symbols["latn"]["decimal"]
122 group = ui_locale.number_symbols["latn"]["group"]
123 query = re.sub(f"[0-9]+[{decimal}|{group}][0-9]+[{decimal}|{group}]?[0-9]?", _decimal, query)
124
125 # only numbers and math operators are accepted
126 if any(str.isalpha(c) for c in query):
127 return results
128
129 # in python, powers are calculated via **
130 query_py_formatted = query.replace("^", "**")
131
132 # Prevent the runtime from being longer than 50 ms
133 res = timeout_func(0.05, _eval_expr, query_py_formatted)
134 if res is None or res == "":
135 return results
136
137 res = babel.numbers.format_decimal(res, locale=ui_locale)
138 results.add(results.types.Answer(answer=f"{search.search_query.query} = {res}"))
139
140 return results
EngineResults post_search(request, search)
Definition calculator.py:97
timeout_func(timeout, func, *args, **kwargs)
Definition calculator.py:79
handler(multiprocessing.Queue q, func, args, **kwargs)
Definition calculator.py:71