You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

switch.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from abc import ABC
  17. from agent.component.base import ComponentBase, ComponentParamBase
  18. class SwitchParam(ComponentParamBase):
  19. """
  20. Define the Switch component parameters.
  21. """
  22. def __init__(self):
  23. super().__init__()
  24. """
  25. {
  26. "logical_operator" : "and | or"
  27. "items" : [
  28. {"cpn_id": "categorize:0", "operator": "contains", "value": ""},
  29. {"cpn_id": "categorize:0", "operator": "contains", "value": ""},...],
  30. "to": ""
  31. }
  32. """
  33. self.conditions = []
  34. self.end_cpn_id = "answer:0"
  35. self.operators = ['contains', 'not contains', 'start with', 'end with', 'empty', 'not empty', '=', '≠', '>',
  36. '<', '≥', '≤']
  37. def check(self):
  38. self.check_empty(self.conditions, "[Switch] conditions")
  39. for cond in self.conditions:
  40. if not cond["to"]:
  41. raise ValueError("[Switch] 'To' can not be empty!")
  42. class Switch(ComponentBase, ABC):
  43. component_name = "Switch"
  44. def get_dependent_components(self):
  45. res = []
  46. for cond in self._param.conditions:
  47. for item in cond["items"]:
  48. if not item["cpn_id"]:
  49. continue
  50. if item["cpn_id"].find("begin") >= 0:
  51. continue
  52. cid = item["cpn_id"].split("@")[0]
  53. res.append(cid)
  54. return list(set(res))
  55. def _run(self, history, **kwargs):
  56. for cond in self._param.conditions:
  57. res = []
  58. for item in cond["items"]:
  59. if not item["cpn_id"]:
  60. continue
  61. cid = item["cpn_id"].split("@")[0]
  62. if item["cpn_id"].find("@") > 0:
  63. cpn_id, key = item["cpn_id"].split("@")
  64. for p in self._canvas.get_component(cid)["obj"]._param.query:
  65. if p["key"] == key:
  66. res.append(self.process_operator(p.get("value",""), item["operator"], item.get("value", "")))
  67. break
  68. else:
  69. out = self._canvas.get_component(cid)["obj"].output()[1]
  70. cpn_input = "" if "content" not in out.columns else " ".join([str(s) for s in out["content"]])
  71. res.append(self.process_operator(cpn_input, item["operator"], item.get("value", "")))
  72. if cond["logical_operator"] != "and" and any(res):
  73. return Switch.be_output(cond["to"])
  74. if all(res):
  75. return Switch.be_output(cond["to"])
  76. return Switch.be_output(self._param.end_cpn_id)
  77. def process_operator(self, input: str, operator: str, value: str) -> bool:
  78. if not isinstance(input, str) or not isinstance(value, str):
  79. raise ValueError('Invalid input or value type: string')
  80. if operator == "contains":
  81. return True if value.lower() in input.lower() else False
  82. elif operator == "not contains":
  83. return True if value.lower() not in input.lower() else False
  84. elif operator == "start with":
  85. return True if input.lower().startswith(value.lower()) else False
  86. elif operator == "end with":
  87. return True if input.lower().endswith(value.lower()) else False
  88. elif operator == "empty":
  89. return True if not input else False
  90. elif operator == "not empty":
  91. return True if input else False
  92. elif operator == "=":
  93. return True if input == value else False
  94. elif operator == "≠":
  95. return True if input != value else False
  96. elif operator == ">":
  97. try:
  98. return True if float(input) > float(value) else False
  99. except Exception:
  100. return True if input > value else False
  101. elif operator == "<":
  102. try:
  103. return True if float(input) < float(value) else False
  104. except Exception:
  105. return True if input < value else False
  106. elif operator == "≥":
  107. try:
  108. return True if float(input) >= float(value) else False
  109. except Exception:
  110. return True if input >= value else False
  111. elif operator == "≤":
  112. try:
  113. return True if float(input) <= float(value) else False
  114. except Exception:
  115. return True if input <= value else False
  116. raise ValueError('Not supported operator' + operator)