.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.plugins.calculator Namespace Reference

Functions

 _eval_expr (expr)
 
 _eval (node)
 
 handler (multiprocessing.Queue q, func, args, **kwargs)
 
 timeout_func (timeout, func, *args, **kwargs)
 
EngineResults post_search (request, search)
 

Variables

str name = "Basic Calculator"
 
 description = gettext("Calculate mathematical expressions via the search bar")
 
bool default_on = True
 
str preference_section = 'general'
 
str plugin_id = 'calculator'
 
dict operators
 
 mp_fork = multiprocessing.get_context("fork")
 

Detailed Description

Calculate mathematical expressions using :py:obj`ast.parse` (mode="eval").

Function Documentation

◆ _eval()

searx.plugins.calculator._eval ( node)
protected

Definition at line 58 of file calculator.py.

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

References _eval().

Referenced by _eval(), and _eval_expr().

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

◆ _eval_expr()

searx.plugins.calculator._eval_expr ( expr)
protected
>>> _eval_expr('2^6')
64
>>> _eval_expr('2**6')
64
>>> _eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0

Definition at line 42 of file calculator.py.

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

References _eval().

+ Here is the call graph for this function:

◆ handler()

searx.plugins.calculator.handler ( multiprocessing.Queue q,
func,
args,
** kwargs )

Definition at line 71 of file calculator.py.

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

◆ post_search()

EngineResults searx.plugins.calculator.post_search ( request,
search )

Definition at line 97 of file calculator.py.

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

References timeout_func().

+ Here is the call graph for this function:

◆ timeout_func()

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

Definition at line 79 of file calculator.py.

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

Referenced by post_search().

+ Here is the caller graph for this function:

Variable Documentation

◆ default_on

bool searx.plugins.calculator.default_on = True

Definition at line 21 of file calculator.py.

◆ description

searx.plugins.calculator.description = gettext("Calculate mathematical expressions via the search bar")

Definition at line 20 of file calculator.py.

◆ mp_fork

searx.plugins.calculator.mp_fork = multiprocessing.get_context("fork")

Definition at line 39 of file calculator.py.

◆ name

str searx.plugins.calculator.name = "Basic Calculator"

Definition at line 19 of file calculator.py.

◆ operators

dict searx.plugins.calculator.operators
Initial value:
1= {
2 ast.Add: operator.add,
3 ast.Sub: operator.sub,
4 ast.Mult: operator.mul,
5 ast.Div: operator.truediv,
6 ast.Pow: operator.pow,
7 ast.BitXor: operator.xor,
8 ast.USub: operator.neg,
9}

Definition at line 25 of file calculator.py.

◆ plugin_id

str searx.plugins.calculator.plugin_id = 'calculator'

Definition at line 23 of file calculator.py.

◆ preference_section

str searx.plugins.calculator.preference_section = 'general'

Definition at line 22 of file calculator.py.