Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

switch.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 _run(self, history, **kwargs):
  44. for cond in self._param.conditions:
  45. if len(cond["items"]) == 1:
  46. out = self._canvas.get_component(cond["items"][0]["cpn_id"])["obj"].output()[1]
  47. cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
  48. if self.process_operator(cpn_input, cond["items"][0]["operator"], cond["items"][0]["value"]):
  49. return Switch.be_output(cond["to"])
  50. continue
  51. if cond["logical_operator"] == "and":
  52. res = True
  53. for item in cond["items"]:
  54. out = self._canvas.get_component(item["cpn_id"])["obj"].output()[1]
  55. cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
  56. if not self.process_operator(cpn_input, item["operator"], item["value"]):
  57. res = False
  58. break
  59. if res:
  60. return Switch.be_output(cond["to"])
  61. continue
  62. res = False
  63. for item in cond["items"]:
  64. out = self._canvas.get_component(item["cpn_id"])["obj"].output()[1]
  65. cpn_input = "" if "content" not in out.columns else " ".join(out["content"])
  66. if self.process_operator(cpn_input, item["operator"], item["value"]):
  67. res = True
  68. break
  69. if res:
  70. return Switch.be_output(cond["to"])
  71. return Switch.be_output(self._param.end_cpn_id)
  72. def process_operator(self, input: str, operator: str, value: str) -> bool:
  73. if not isinstance(input, str) or not isinstance(value, str):
  74. raise ValueError('Invalid input or value type: string')
  75. if operator == "contains":
  76. return True if value.lower() in input.lower() else False
  77. elif operator == "not contains":
  78. return True if value.lower() not in input.lower() else False
  79. elif operator == "start with":
  80. return True if input.lower().startswith(value.lower()) else False
  81. elif operator == "end with":
  82. return True if input.lower().endswith(value.lower()) else False
  83. elif operator == "empty":
  84. return True if not input else False
  85. elif operator == "not empty":
  86. return True if input else False
  87. elif operator == "=":
  88. return True if input == value else False
  89. elif operator == "≠":
  90. return True if input != value else False
  91. elif operator == ">":
  92. try:
  93. return True if float(input) > float(value) else False
  94. except Exception as e:
  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 as e:
  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 as e:
  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 as e:
  110. return True if input <= value else False
  111. raise ValueError('Not supported operator' + operator)