Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Udayraj123
GitHub Repository: Udayraj123/OMRChecker
Path: blob/master/src/processors/manager.py
214 views
1
"""
2
Processor/Extension framework
3
Adapated from https://github.com/gdiepen/python_processor_example
4
"""
5
import inspect
6
import pkgutil
7
8
from src.logger import logger
9
10
11
class Processor:
12
"""Base class that each processor must inherit from."""
13
14
def __init__(
15
self,
16
options=None,
17
relative_dir=None,
18
image_instance_ops=None,
19
):
20
self.options = options
21
self.relative_dir = relative_dir
22
self.image_instance_ops = image_instance_ops
23
self.tuning_config = image_instance_ops.tuning_config
24
self.description = "UNKNOWN"
25
26
27
class ProcessorManager:
28
"""Upon creation, this class will read the processors package for modules
29
that contain a class definition that is inheriting from the Processor class
30
"""
31
32
def __init__(self, processors_dir="src.processors"):
33
"""Constructor that initiates the reading of all available processors
34
when an instance of the ProcessorCollection object is created
35
"""
36
self.processors_dir = processors_dir
37
self.reload_processors()
38
39
@staticmethod
40
def get_name_filter(processor_name):
41
def filter_function(member):
42
return inspect.isclass(member) and member.__module__ == processor_name
43
44
return filter_function
45
46
def reload_processors(self):
47
"""Reset the list of all processors and initiate the walk over the main
48
provided processor package to load all available processors
49
"""
50
self.processors = {}
51
self.seen_paths = []
52
53
logger.info(f'Loading processors from "{self.processors_dir}"...')
54
self.walk_package(self.processors_dir)
55
56
def walk_package(self, package):
57
"""walk the supplied package to retrieve all processors"""
58
imported_package = __import__(package, fromlist=["blah"])
59
loaded_packages = []
60
for _, processor_name, ispkg in pkgutil.walk_packages(
61
imported_package.__path__, imported_package.__name__ + "."
62
):
63
if not ispkg and processor_name != __name__:
64
processor_module = __import__(processor_name, fromlist=["blah"])
65
# https://stackoverflow.com/a/46206754/6242649
66
clsmembers = inspect.getmembers(
67
processor_module,
68
ProcessorManager.get_name_filter(processor_name),
69
)
70
for _, c in clsmembers:
71
# Only add classes that are a sub class of Processor, but NOT Processor itself
72
if issubclass(c, Processor) & (c is not Processor):
73
self.processors[c.__name__] = c
74
loaded_packages.append(c.__name__)
75
76
logger.info(f"Loaded processors: {loaded_packages}")
77
78
79
# Singleton export
80
PROCESSOR_MANAGER = ProcessorManager()
81
82