calculator.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Calculate mathematical expressions using ack#eval
  3. """
  4. import ast
  5. import operator
  6. from flask_babel import gettext
  7. from searx import settings
  8. name = "Basic Calculator"
  9. description = gettext("Calculate mathematical expressions via the search bar")
  10. default_on = False
  11. preference_section = 'general'
  12. plugin_id = 'calculator'
  13. operators = {
  14. ast.Add: operator.add,
  15. ast.Sub: operator.sub,
  16. ast.Mult: operator.mul,
  17. ast.Div: operator.truediv,
  18. ast.Pow: operator.pow,
  19. ast.BitXor: operator.xor,
  20. ast.USub: operator.neg,
  21. }
  22. def _eval_expr(expr):
  23. """
  24. >>> _eval_expr('2^6')
  25. 4
  26. >>> _eval_expr('2**6')
  27. 64
  28. >>> _eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  29. -5.0
  30. """
  31. return _eval(ast.parse(expr, mode='eval').body)
  32. def _eval(node):
  33. if isinstance(node, ast.Constant) and isinstance(node.value, int):
  34. return node.value
  35. if isinstance(node, ast.BinOp):
  36. return operators[type(node.op)](_eval(node.left), _eval(node.right))
  37. if isinstance(node, ast.UnaryOp):
  38. return operators[type(node.op)](_eval(node.operand))
  39. raise TypeError(node)
  40. def post_search(_request, search):
  41. # don't run on public instances due to possible attack surfaces
  42. if settings['server']['public_instance']:
  43. return True
  44. # only show the result of the expression on the first page
  45. if search.search_query.pageno > 1:
  46. return True
  47. query = search.search_query.query
  48. # in order to avoid DoS attacks with long expressions, ignore long expressions
  49. if len(query) > 100:
  50. return True
  51. # replace commonly used math operators with their proper Python operator
  52. query = query.replace("x", "*").replace(":", "/")
  53. # only numbers and math operators are accepted
  54. if any(str.isalpha(c) for c in query):
  55. return True
  56. # in python, powers are calculated via **
  57. query_py_formatted = query.replace("^", "**")
  58. try:
  59. result = str(_eval_expr(query_py_formatted))
  60. if result != query:
  61. search.result_container.answers['calculate'] = {'answer': f"{query} = {result}"}
  62. except (TypeError, SyntaxError, ArithmeticError):
  63. pass
  64. return True
  65. def is_allowed():
  66. return not settings['server']['public_instance']