forked from GEM-benchmark/NL-Augmenter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestRunner.py
175 lines (151 loc) Β· 6.24 KB
/
TestRunner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import inspect
import json
import os
import re
from importlib import import_module
from pathlib import Path
from pkgutil import iter_modules
from typing import Iterable
from interfaces.Operation import Operation
from tasks.TaskTypes import TaskType
def load(module, cls):
my_class = getattr(module, cls.__name__)
return my_class()
def load_test_cases(test_json):
try:
with open(test_json) as f:
d = json.load(f)
examples = d["test_cases"]
return examples
except FileNotFoundError:
raise Exception(
f"\n\n\t\tYou should add a test file at this location!\n\t\t{test_json}"
)
def convert_to_snake_case(camel_case):
name = re.sub(r"(?<!^)(?=[A-Z])", "_", camel_case).lower()
return name
class OperationRuns(object):
def __init__(self, transformation_name, search="transformations"):
if transformation_name == "light":
self._load_all_transformation_test_case(heavy=False, search=search)
elif transformation_name == "all":
self._load_all_transformation_test_case(heavy=True, search=search)
else:
self._load_single_transformation_test_case(
transformation_name, search
)
def _load_single_transformation_test_case(
self, transformation_name, search="transformations"
):
filters = []
filter_test_cases = []
package_dir = Path(__file__).resolve() # --> TestRunner.py
filters_dir = package_dir.parent.joinpath(search, transformation_name)
t_py = import_module(f"{search}.{transformation_name}")
t_js = os.path.join(filters_dir, "test.json")
filter_instance = None
prev_class_args = {}
for test_case in load_test_cases(t_js):
class_name = test_case["class"]
class_args = test_case["args"] if "args" in test_case else {}
# construct filter class with input args
cls = getattr(t_py, class_name)
if (
filter_instance is None
or filter_instance.name() != class_name
or prev_class_args != class_args
):
filter_instance = cls(**class_args)
prev_class_args = class_args
filters.append(filter_instance)
filter_test_cases.append(test_case)
self.operations = filters
self.operation_test_cases = filter_test_cases
def _load_all_transformation_test_case(
self, heavy=False, search="transformations"
):
filters = []
filter_test_cases = []
package_dir = Path(__file__).resolve() # --> TestRunner.py
filters_dir = package_dir.parent.joinpath(search)
for (_, m, _) in iter_modules([filters_dir]):
t_py = import_module(f"{search}.{m}")
t_js = os.path.join(filters_dir, m, "test.json")
filter_instance = None
prev_class_args = {}
for test_case in load_test_cases(t_js):
class_name = test_case["class"]
class_args = test_case["args"] if "args" in test_case else {}
cls = getattr(t_py, class_name)
is_heavy = cls.is_heavy()
if (not heavy) and is_heavy:
continue
else:
# Check if the same instance (i.e. with the same args is already loaded)
if (
filter_instance is None
or filter_instance.name() != class_name
or prev_class_args != class_args
):
filter_instance = cls(**class_args)
prev_class_args = class_args
filters.append(filter_instance)
filter_test_cases.append(test_case)
self.operations = filters
self.operation_test_cases = filter_test_cases
@staticmethod
def get_all_folder_names(search="transformations") -> Iterable:
# iterate through the modules in the current package
package_dir = Path(__file__).resolve() # --> TestRunner.py
transformations_dir = package_dir.parent.joinpath(search)
for (_, folder, _) in iter_modules(
[transformations_dir]
): # ---> ["back_translation", ...]
yield folder
@staticmethod
def get_all_operations(search="transformations") -> Iterable:
# iterate through the modules in the current package
package_dir = Path(__file__).resolve() # --> TestRunner.py
transformations_dir = package_dir.parent.joinpath(search)
for (_, folder, _) in iter_modules(
[transformations_dir]
): # ---> ["back_translation", ...]
t_py = import_module(f"{search}.{folder}")
for name, obj in inspect.getmembers(t_py):
if (
inspect.isclass(obj)
and issubclass(obj, Operation)
and not obj.__module__.startswith("interfaces")
):
yield obj
@staticmethod
def get_all_operations_for_task(
query_task_type: TaskType, search="transformations"
) -> Iterable:
# iterate through the modules in the current package
for operation in OperationRuns.get_all_operations(search):
if query_task_type in operation.tasks:
yield operation
def get_implementation(clazz: str, search="transformations"):
for operation in OperationRuns.get_all_operations(search):
if operation.name() == clazz:
return operation
raise ValueError(
f"No class called {clazz} found in the {search} folder. Check if you've spelled it right!"
)
if __name__ == "__main__":
for x in OperationRuns.get_all_folder_names():
print(x)
for x in OperationRuns.get_all_folder_names("filters"):
print(x)
for x in OperationRuns.get_all_operations():
print(x)
for x in OperationRuns.get_all_operations("filters"):
print(x)
print()
for transformation in OperationRuns.get_all_operations_for_task(
TaskType.QUESTION_ANSWERING
):
print(transformation.name())
impl = transformation()
print(impl.generate("context", "question", ["answer1", "answerN"]))