austindavis commited on
Commit
3b28800
·
verified ·
1 Parent(s): 488376b

Create dataset_generation/command_pattern.py

Browse files
src/dataset_generation/command_pattern.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module defines a command pattern framework. It includes the abstract Command class
3
+ for defining specific commands and a CommandExecutor class to register and execute these commands.
4
+
5
+
6
+ Example usage:
7
+ ```
8
+ if __name__ == "__main__":
9
+ class MyCommand(Command):
10
+ def execute(self, *args, **kwargs):
11
+ print(f"Executing MyCommand with args: {args}, kwargs: {kwargs}")
12
+
13
+ def add_arguments(self, parser):
14
+ parser.add_argument('--myarg', type=int, help="An integer argument")
15
+
16
+ executor = CommandExecutor()
17
+ executor.register('mycommand', MyCommand())
18
+
19
+ parser = argparse.ArgumentParser(description="Command pattern example")
20
+ executor.add_commands_to_argparser(parser)
21
+ args = parser.parse_args()
22
+ executor.execute_from_args(args)
23
+ ```
24
+ """
25
+
26
+ import abc
27
+ import argparse
28
+ from typing import NoReturn
29
+
30
+
31
+ class AbstractCommand(abc.ABC):
32
+ """
33
+ Abstract base class for commands. Any specific command should inherit from this class and
34
+ implement the execute method.
35
+ """
36
+
37
+ @abc.abstractmethod
38
+ def execute(self, *args, **kwargs) -> NoReturn:
39
+ """
40
+ Execute the command with optional positional and keyword arguments.
41
+
42
+ Args:
43
+ *args: Positional arguments for the command.
44
+ **kwargs: Keyword arguments for the command.
45
+ """
46
+ pass
47
+
48
+ def help_str(self) -> str:
49
+ """
50
+ Returns a help string, suitable for use with an ArgumentParser.
51
+ """
52
+ return self.__class__.__doc__
53
+
54
+ def add_arguments(self, parser: argparse.ArgumentParser) -> NoReturn:
55
+ """
56
+ Add command-specific arguments to the parser.
57
+
58
+ Args: parser (argparse.ArgumentParser) The parser to add arguments to."""
59
+ pass
60
+
61
+ class CommandExecutor:
62
+ """
63
+ CommandExecutor manages the registration and execution of commands.
64
+ """
65
+
66
+ def __init__(self, command_dict: dict[str,AbstractCommand] = {}):
67
+ """
68
+ Initialize the CommandExecutor with an optional dictionary of commands.
69
+
70
+ Args:
71
+ command_dict (dict): A dictionary where keys are command names and values are Command instances.
72
+ """
73
+ self.commands = command_dict
74
+
75
+ def register(self, command_name: str, command: AbstractCommand):
76
+ """
77
+ Register a command with a specified name.
78
+
79
+ Args:
80
+ command_name (str): The name of the command to register.
81
+ command (Command): The Command instance to register.
82
+ """
83
+ self.commands[command_name] = command
84
+
85
+
86
+ def execute(self, command_name: str, *args, **kwargs):
87
+ """
88
+ Execute the command registered under the given name.
89
+
90
+ Args:
91
+ command_name (str): The name of the command to execute.
92
+
93
+ Raises:
94
+ ValueError: If the command name is not registered.
95
+ """
96
+ command = self.commands.get(command_name)
97
+ if command:
98
+ command.execute(*args,**kwargs)
99
+ else:
100
+ raise ValueError(
101
+ f"Command '{command_name}' is not registered with this executor."
102
+ )
103
+
104
+ def execute_from_args(self, namespace: argparse.Namespace, *args, **kwargs):
105
+ """
106
+ Execute the first active command based on the argparse Namespace.
107
+
108
+ Args:
109
+ namespace (argparse.Namespace): Namespace containing command line arguments.
110
+ """
111
+
112
+ for cmd_name, is_active in [
113
+ (cmd_key, cmd_key in namespace.__dict__.values()) for cmd_key in self.get_registered_commands()
114
+ ]:
115
+ if is_active:
116
+ self.execute(cmd_name, namespace)
117
+ break
118
+
119
+ def add_commands_to_argparser(self, parser: argparse.ArgumentParser):
120
+ subparsers = parser.add_subparsers(dest="command", help="Sub-command help")
121
+
122
+ for name, command in self.commands.items():
123
+ cmd_specific_parser = subparsers.add_parser(name, help=command.help_str())
124
+ cmd_specific_parser.description = command.__class__.__doc__
125
+ command.add_arguments(cmd_specific_parser)
126
+
127
+ return parser
128
+
129
+ def get_registered_commands(self):
130
+ """
131
+ Get a list of all registered command names.
132
+
133
+ Returns:
134
+ list: A list of registered command names.
135
+ """
136
+ return list(self.commands.keys())
137
+
138
+ def __repr__(self):
139
+ """
140
+ Return a string representation of the CommandExecutor, listing all registered commands.
141
+
142
+ Returns:
143
+ str: A string representation of the CommandExecutor.
144
+ """
145
+ return f"Registered Commands: {self.get_registered_commands()}"
146
+
147
+
148
+ class SequentialCommandExecutor(CommandExecutor):
149
+ def execute_from_args(self, namespace: argparse.Namespace, *args, **kwargs):
150
+ """
151
+ Execute the all active commands based on the argparse Namespace.
152
+
153
+ Args:
154
+ namespace (argparse.Namespace): Namespace containing command line arguments.
155
+ """
156
+
157
+ for cmd_name, is_active in [
158
+ (c, namespace.__dict__[c]) for c in self.get_registered_commands()
159
+ ]:
160
+ if is_active:
161
+ self.execute(cmd_name, namespace)
162
+
163
+ def add_commands_to_argparser(self, parser: argparse.ArgumentParser):
164
+ help_txt_suffix = "\nThis script has several modes: \n\n"+str(list(self.commands.keys()))
165
+ parser.description += help_txt_suffix #"\rn\t".join(help_txt_suffix)
166
+
167
+ for name, command in self.commands.items():
168
+ parser.add_argument(
169
+ f"--{name}", action="store_true", help=command.help_str()
170
+ )
171
+
172
+ return parser