eval_context.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. from typing import TYPE_CHECKING, get_origin, get_args
  2. from types import UnionType
  3. from uuid import UUID
  4. from jinja2 import Template
  5. from framework.conformance import eval_context_decorator
  6. from services.primitives.string_type import String
  7. if TYPE_CHECKING:
  8. from api.od_stub_readonly import get_outgoing, get_incoming, get_slot_value, get_value, get_target, has_slot
  9. from eval_context_stub import *
  10. @eval_context_decorator
  11. def _check_all_connections(this, labels: list[list[str] | str]) -> list[str]:
  12. err = []
  13. check_incoming_exec(this, err, labels[0])
  14. check_outgoing_exec(this, err, labels[1])
  15. check_incoming_data(this, err, labels[2])
  16. check_outgoing_data(this, err, labels[3])
  17. return err
  18. @eval_context_decorator
  19. def _check_outgoing_exec(this, err: list[str], labels: list[str]) -> None:
  20. l = set(labels)
  21. gates = set()
  22. for y in get_outgoing(this, "Conn_exec"):
  23. if (x := get_slot_value(y, "from")) not in l:
  24. err.append(f"output exec gate '{x}' does not exist. Gates: {', '.join(labels)}.")
  25. if x in gates:
  26. err.append(f"output exec gate '{x}' is connected to multiple gates.")
  27. gates.add(x)
  28. @eval_context_decorator
  29. def _check_incoming_exec(this, err: list[str], labels: list[str]) -> None:
  30. l = set(labels)
  31. for y in get_incoming(this, "Conn_exec"):
  32. if (x := get_slot_value(y, "to")) not in l:
  33. err.append(f"input exec gate gate '{x}' does not exist. Gates: {', '.join(labels)}.")
  34. @eval_context_decorator
  35. def _check_outgoing_data(this, err: list[str], labels: list[str]) -> None:
  36. l = set(labels)
  37. for y in get_outgoing(this, "Conn_data"):
  38. if (x := get_slot_value(y, "from")) not in l:
  39. err.append(f"output data gate '{x}' does not exist. Gates: {', '.join(labels)}.")
  40. @eval_context_decorator
  41. def _check_incoming_data(this, err: list[str], labels: list[str]) -> None:
  42. l = set(labels)
  43. gates = set()
  44. for y in get_incoming(this, "Conn_data"):
  45. if (x := get_slot_value(y, "to")) not in l:
  46. err.append(f"input data gate '{x}' does not exist. Gates: {', '.join(labels)}.")
  47. if x in gates:
  48. err.append(f"input data gate '{x}' is connected to multiple gates.")
  49. gates.add(x)
  50. def check_type(x: any, typ2: any) -> bool:
  51. origin = get_origin(typ2)
  52. if origin is None:
  53. return isinstance(x, typ2)
  54. args = get_args(typ2)
  55. if origin is UnionType:
  56. for tp in args:
  57. if check_type(x, tp):
  58. return True
  59. return False
  60. if not isinstance(x, origin):
  61. return False
  62. if origin in [list, set]:
  63. for value in x:
  64. if not check_type(value, args[0]):
  65. return False
  66. elif origin is tuple:
  67. if len(args) != len(x):
  68. return False
  69. for i, value in enumerate(x):
  70. if not check_type(value, args[i]):
  71. return False
  72. elif origin is dict:
  73. for key, value in x.items():
  74. if not (check_type(key, args[0]) and check_type(value, args[1])):
  75. return False
  76. return True
  77. @eval_context_decorator
  78. def _check_slot_code_type(this: UUID, slot: str, typ: type, unique = False, *, mandatory: bool = False, blacklist: list[str] | None = None) -> list[str]:
  79. err = []
  80. if not (has_slot(this, slot)):
  81. if mandatory:
  82. err.append(f"Missing mandatory slot: '{slot}'.")
  83. return err
  84. try:
  85. try:
  86. x = eval(get_slot_value(this, slot))
  87. except Exception as _:
  88. err.append(f"Invalid python code for {slot}: {get_slot_value(this, slot)}")
  89. return err
  90. if not check_type(x, typ):
  91. try:
  92. typ_rep = typ.__name__
  93. except AttributeError:
  94. typ_rep = str(typ)
  95. err.append(f"Unexpected type for {slot}: {type(x).__name__}, expected type: {typ_rep}")
  96. return err
  97. if unique and len(set(x)) != len(x):
  98. err.append(f"elements must be unique")
  99. return err
  100. except Exception as e:
  101. err.append(f"Unexpected error: {e}")
  102. return err
  103. @eval_context_decorator
  104. def _check_jinja2_code(this: UUID, slot: str) -> list[str]:
  105. if len(err:= check_slot_code_type(this, slot, str, mandatory=True)) != 0:
  106. return err
  107. s = eval(get_slot_value(this, slot))
  108. try:
  109. template = Template(s)
  110. template.render(**{"data":[{}]})
  111. return []
  112. except Exception as e:
  113. return [f"Invalid Jinja2 syntax for '{slot}':\n{e}\n{s}"]
  114. @eval_context_decorator
  115. def _check_code_syntax(code) -> list[str]:
  116. try:
  117. compile(code, "<string>", "exec")
  118. return []
  119. except SyntaxError as e:
  120. return [f"Invalid python code for: `{code}` :\n{e}"]
  121. mm_eval_context = {
  122. "check_all_connections": _check_all_connections,
  123. "check_outgoing_exec": _check_outgoing_exec,
  124. "check_incoming_exec": _check_incoming_exec,
  125. "check_outgoing_data": _check_outgoing_data,
  126. "check_incoming_data": _check_incoming_data,
  127. "check_slot_code_type": _check_slot_code_type,
  128. "check_code_syntax": _check_code_syntax,
  129. "check_jinja2_code": _check_jinja2_code,
  130. }