소스 검색

chore(core/workflow/utils/variable_template_parser): Refactor VariableTemplateParser class for better readability and maintainability. (#5328)

tags/0.6.12
-LAN- 1 년 전
부모
커밋
54756cd3b2
No account linked to committer's email address
1개의 변경된 파일55개의 추가작업 그리고 0개의 파일을 삭제
  1. 55
    0
      api/core/workflow/utils/variable_template_parser.py

+ 55
- 0
api/core/workflow/utils/variable_template_parser.py 파일 보기



class VariableTemplateParser: class VariableTemplateParser:
""" """
A class for parsing and manipulating template variables in a string.

Rules: Rules:


1. Template variables must be enclosed in `{{}}`. 1. Template variables must be enclosed in `{{}}`.
2. The template variable Key can only be: #node_id.var1.var2#. 2. The template variable Key can only be: #node_id.var1.var2#.
3. The template variable Key cannot contain new lines or spaces, and must comply with rule 2. 3. The template variable Key cannot contain new lines or spaces, and must comply with rule 2.

Example usage:

template = "Hello, {{#node_id.query.name#}}! Your age is {{#node_id.query.age#}}."
parser = VariableTemplateParser(template)

# Extract template variable keys
variable_keys = parser.extract()
print(variable_keys)
# Output: ['#node_id.query.name#', '#node_id.query.age#']

# Extract variable selectors
variable_selectors = parser.extract_variable_selectors()
print(variable_selectors)
# Output: [VariableSelector(variable='#node_id.query.name#', value_selector=['node_id', 'query', 'name']),
# VariableSelector(variable='#node_id.query.age#', value_selector=['node_id', 'query', 'age'])]

# Format the template string
inputs = {'#node_id.query.name#': 'John', '#node_id.query.age#': 25}}
formatted_string = parser.format(inputs)
print(formatted_string)
# Output: "Hello, John! Your age is 25."
""" """


def __init__(self, template: str): def __init__(self, template: str):
self.variable_keys = self.extract() self.variable_keys = self.extract()


def extract(self) -> list: def extract(self) -> list:
"""
Extracts all the template variable keys from the template string.

Returns:
A list of template variable keys.
"""
# Regular expression to match the template rules # Regular expression to match the template rules
matches = re.findall(REGEX, self.template) matches = re.findall(REGEX, self.template)


return list(set(first_group_matches)) return list(set(first_group_matches))


def extract_variable_selectors(self) -> list[VariableSelector]: def extract_variable_selectors(self) -> list[VariableSelector]:
"""
Extracts the variable selectors from the template variable keys.

Returns:
A list of VariableSelector objects representing the variable selectors.
"""
variable_selectors = [] variable_selectors = []
for variable_key in self.variable_keys: for variable_key in self.variable_keys:
remove_hash = variable_key.replace('#', '') remove_hash = variable_key.replace('#', '')
return variable_selectors return variable_selectors


def format(self, inputs: dict, remove_template_variables: bool = True) -> str: def format(self, inputs: dict, remove_template_variables: bool = True) -> str:
"""
Formats the template string by replacing the template variables with their corresponding values.

Args:
inputs: A dictionary containing the values for the template variables.
remove_template_variables: A boolean indicating whether to remove the template variables from the output.

Returns:
The formatted string with template variables replaced by their values.
"""
def replacer(match): def replacer(match):
key = match.group(1) key = match.group(1)
value = inputs.get(key, match.group(0)) # return original matched string if key not found value = inputs.get(key, match.group(0)) # return original matched string if key not found


@classmethod @classmethod
def remove_template_variables(cls, text: str): def remove_template_variables(cls, text: str):
"""
Removes the template variables from the given text.

Args:
text: The text from which to remove the template variables.

Returns:
The text with template variables removed.
"""
return re.sub(REGEX, r'{\1}', text) return re.sub(REGEX, r'{\1}', text)

Loading…
취소
저장