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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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"]: raise ValueError(f"[Switch] 'To' can not be empty!")
  41. class Switch(ComponentBase, ABC):
  42. component_name = "Switch"
  43. def get_dependent_components(self):
  44. res = []
  45. for cond in self._param.conditions:
  46. for item in cond["items"]:
  47. if not item["cpn_id"]: continue
  48. if item["cpn_id"].find("begin") >= 0:
  49. continue
  50. cid = item["cpn_id"].split("@")[0]
  51. res.append(cid)
  52. return list(set(res))
  53. def _run(self, history, **kwargs):
  54. for cond in self._param.conditions:
  55. res = []
  56. for item in cond["items"]:
  57. if not item["cpn_id"]:continue
  58. cid = item["cpn_id"].split("@")[0]
  59. if item["cpn_id"].find("@") > 0:
  60. cpn_id, key = item["cpn_id"].split("@")
  61. for p in self._canvas.get_component(cid)["obj"]._param.query:
  62. if p["key"] == key:
  63. res.append(self.process_operator(p.get("value",""), item["operator"], item.get("value", "")))
  64. break
  65. else:
  66. out = self._canvas.get_component(cid)["obj"].output()[1]
  67. cpn_input = "" if "content" not in out.columns else " ".join([str(s) for s in out["content"]])
  68. res.append(self.process_operator(cpn_input, item["operator"], item.get("value", "")))
  69. if cond["logical_operator"] != "and" and any(res):
  70. return Switch.be_output(cond["to"])
  71. if all(res):
  72. return Switch.be_output(cond["to"])
  73. return Switch.be_output(self._param.end_cpn_id)
  74. def process_operator(self, input: str, operator: str, value: str) -> bool:
  75. if not isinstance(input, str) or not isinstance(value, str):
  76. raise ValueError('Invalid input or value type: string')
  77. if operator == "contains":
  78. return True if value.lower() in input.lower() else False
  79. elif operator == "not contains":
  80. return True if value.lower() not in input.lower() else False
  81. elif operator == "start with":
  82. return True if input.lower().startswith(value.lower()) else False
  83. elif operator == "end with":
  84. return True if input.lower().endswith(value.lower()) else False
  85. elif operator == "empty":
  86. return True if not input else False
  87. elif operator == "not empty":
  88. return True if input else False
  89. elif operator == "=":
  90. return True if input == value else False
  91. elif operator == "≠":
  92. return True if input != value else False
  93. elif operator == ">":
  94. try:
  95. return True if float(input) > float(value) else False
  96. except Exception as e:
  97. return True if input > value else False
  98. elif operator == "<":
  99. try:
  100. return True if float(input) < float(value) else False
  101. except Exception as e:
  102. return True if input < value else False
  103. elif operator == "≥":
  104. try:
  105. return True if float(input) >= float(value) else False
  106. except Exception as e:
  107. return True if input >= value else False
  108. elif operator == "≤":
  109. try:
  110. return True if float(input) <= float(value) else False
  111. except Exception as e:
  112. return True if input <= value else False
  113. raise ValueError('Not supported operator' + operator)