calculator.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Calculate mathematical expressions using ack#eval
  3. """
  4. import ast
  5. import re
  6. import operator
  7. from multiprocessing import Process, Queue
  8. from typing import Callable
  9. import babel.numbers
  10. from flask_babel import gettext
  11. from searx.plugins import logger
  12. name = "Basic Calculator"
  13. description = gettext("Calculate mathematical expressions via the search bar")
  14. default_on = True
  15. preference_section = 'general'
  16. plugin_id = 'calculator'
  17. logger = logger.getChild(plugin_id)
  18. operators: dict[type, Callable] = {
  19. ast.Add: operator.add,
  20. ast.Sub: operator.sub,
  21. ast.Mult: operator.mul,
  22. ast.Div: operator.truediv,
  23. ast.Pow: operator.pow,
  24. ast.BitXor: operator.xor,
  25. ast.USub: operator.neg,
  26. }
  27. def _eval_expr(expr):
  28. """
  29. >>> _eval_expr('2^6')
  30. 4
  31. >>> _eval_expr('2**6')
  32. 64
  33. >>> _eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  34. -5.0
  35. """
  36. try:
  37. return _eval(ast.parse(expr, mode='eval').body)
  38. except ZeroDivisionError:
  39. # This is undefined
  40. return ""
  41. def _eval(node):
  42. if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
  43. return node.value
  44. if isinstance(node, ast.BinOp):
  45. return operators[type(node.op)](_eval(node.left), _eval(node.right))
  46. if isinstance(node, ast.UnaryOp):
  47. return operators[type(node.op)](_eval(node.operand))
  48. raise TypeError(node)
  49. def timeout_func(timeout, func, *args, **kwargs):
  50. def handler(q: Queue, func, args, **kwargs): # pylint:disable=invalid-name
  51. try:
  52. q.put(func(*args, **kwargs))
  53. except:
  54. q.put(None)
  55. raise
  56. que = Queue()
  57. p = Process(target=handler, args=(que, func, args), kwargs=kwargs)
  58. p.start()
  59. p.join(timeout=timeout)
  60. ret_val = None
  61. if not p.is_alive():
  62. ret_val = que.get()
  63. else:
  64. logger.debug("terminate function after timeout is exceeded")
  65. p.terminate()
  66. p.join()
  67. p.close()
  68. return ret_val
  69. def post_search(_request, search):
  70. # only show the result of the expression on the first page
  71. if search.search_query.pageno > 1:
  72. return True
  73. query = search.search_query.query
  74. # in order to avoid DoS attacks with long expressions, ignore long expressions
  75. if len(query) > 100:
  76. return True
  77. # replace commonly used math operators with their proper Python operator
  78. query = query.replace("x", "*").replace(":", "/")
  79. # parse the number system in a localized way
  80. def _decimal(match: re.Match) -> str:
  81. val = match.string[match.start() : match.end()]
  82. val = babel.numbers.parse_decimal(val, search.search_query.locale, numbering_system="latn")
  83. return str(val)
  84. decimal = search.search_query.locale.number_symbols["latn"]["decimal"]
  85. group = search.search_query.locale.number_symbols["latn"]["group"]
  86. query = re.sub(f"[0-9]+[{decimal}|{group}][0-9]+[{decimal}|{group}]?[0-9]?", _decimal, query)
  87. # only numbers and math operators are accepted
  88. if any(str.isalpha(c) for c in query):
  89. return True
  90. # in python, powers are calculated via **
  91. query_py_formatted = query.replace("^", "**")
  92. # Prevent the runtime from being longer than 50 ms
  93. result = timeout_func(0.05, _eval_expr, query_py_formatted)
  94. if result is None or result == "":
  95. return True
  96. result = babel.numbers.format_decimal(result, locale=search.search_query.locale)
  97. search.result_container.answers['calculate'] = {'answer': f"{search.search_query.query} = {result}"}
  98. return True