Skip to content

Conditional

ConditionalExtract

Bases: ExtractionMethod

Method to run set of extraction methods given a condition.

Method name: conditional

Example Configuration

.. code-block:: yaml

- method: conditional
  inputs:
    condition: $foo == bar
    true_methods:
      - method: default
        inputs:
          defaults:
            hello: world
    false_methods:
      - method: default
        inputs:
          defaults:
            hello: there
Source code in extraction_methods/plugins/conditional.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class ConditionalExtract(ExtractionMethod):
    """
    Method to run set of extraction methods given a condition.

    **Method name:** ``conditional``

    Example Configuration:
        .. code-block:: yaml

            - method: conditional
              inputs:
                condition: $foo == bar
                true_methods:
                  - method: default
                    inputs:
                      defaults:
                        hello: world
                false_methods:
                  - method: default
                    inputs:
                      defaults:
                        hello: there
    """

    input_class = ConditionalInput

    @update_input
    def run(self, body: dict[str, Any]) -> dict[str, Any]:

        condition = ""
        for term in self.input.condition.split(" "):

            if term[0] == self.input.exists_key:
                term = body.get(term[1:], None)

                if isinstance(term, str):
                    term = f"'{term}'"

            condition += f" {term}"

        extraction_methods = (
            self.input.true_methods
            if bool(eval(condition))  # nosec B307
            else self.input.false_methods
        )

        for extraction_method in extraction_methods:
            body = extraction_method._run(body)

        return body

ConditionalInput

Bases: Input

Model for Conditional Method Input.

Parameters:

Name Type Description Default
condition str

Condition to decide on which methods are run.

required
true_methods list[ExtractionMethodConf]

Extraction methods to run if contition is true.

[]
false_methods list[ExtractionMethodConf]

Extraction methods to run if contition is false.

[]
Source code in extraction_methods/plugins/conditional.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class ConditionalInput(Input):
    """
    Model for Conditional Method Input.
    """

    condition: str = Field(
        description="Condition to decide on which methods are run.",
    )
    true_methods: list[ExtractionMethodConf] = Field(
        default=[],
        description="Extraction methods to run if contition is true.",
    )
    false_methods: list[ExtractionMethodConf] = Field(
        default=[],
        description="Extraction methods to run if contition is false.",
    )