Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit f0b4a54b authored by Nivesh Krishna's avatar Nivesh Krishna
Browse files

set timeout to calculator

parent 38fb37cf
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -20,3 +20,4 @@ linuxdoc==20211220
aiounittest==1.4.1
numexpr==2.8.1
werkzeug==2.0.3
wrapt-timeout-decorator==1.3.8
+1 −0
Original line number Diff line number Diff line
@@ -18,3 +18,4 @@ redis==3.4.1
ring==0.7.3
numexpr==2.8.1
werkzeug==2.0.3
wrapt-timeout-decorator==1.3.8
 No newline at end of file
+7 −14
Original line number Diff line number Diff line
from searx import logger
from numexpr import evaluate
from flask_babel import gettext

from wrapt_timeout_decorator import timeout

name = gettext('Calculator')
description = gettext('This plugin extends results when the query is a mathematical expression')
@@ -13,13 +13,10 @@ def check_if_loaded():
    logger.debug("initializing calculator plugin")


def is_really_big(query):
    # For cases like 2**99999**9999
    if len(query.split("**")) >= 3:
        return True
    # Add more cases if needed
    return False

# Set timeout so that the plugin doesn't hang for long computations
@timeout(5)
def calculate(query):
    return evaluate(query).item()

def post_search(request, search):
    if search.search_query.pageno > 1:
@@ -45,16 +42,12 @@ def post_search(request, search):
        if len(query) > 30:
            return

        # Not going to compute the result if the query is not within permissible range
        if is_really_big(query):
            raise OverflowError

        value = evaluate(query).item()
        value = calculate(query)
        if type(value) in (int, float):
            search.result_container.answers.clear()
            answer = "{} = {}".format(unmodified_query, value)
            search.result_container.answers[answer] = {'answer': answer, 'calculator': True}
    except (ZeroDivisionError, ValueError, FloatingPointError, MemoryError, OverflowError) as e:
    except (ZeroDivisionError, ValueError, FloatingPointError, MemoryError, OverflowError, TimeoutError) as e:
        answer = gettext('Error')
        search.result_container.answers[answer] = {'answer': answer, 'calculator': True}
    except Exception as e: