-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathattributeConverter.py
More file actions
102 lines (82 loc) · 3.4 KB
/
Copy pathattributeConverter.py
File metadata and controls
102 lines (82 loc) · 3.4 KB
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
"""
attributeConverter: base descriptors class for AttributeConverter nodes
"""
import logging
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, ClassVar
from collections import defaultdict
from itertools import chain
if TYPE_CHECKING:
from meshroom.core.desc.attribute import Attribute
class AttributeConverter(ABC):
"""
Base class for converting the value of a source Attribute
into a value for a destination Attribute of a different type,
so a connection can be made between them.
"""
name: ClassVar[str] = ""
description: ClassVar[str] = ""
priority: ClassVar[int] = 10 # Put a higher number to prioritize specific converters
# Input / Output classes
srcType: ClassVar["Attribute"] = None
dstType: ClassVar["Attribute"] = None
def __init__(self):
if not all ((self.srcType, self.dstType)):
raise TypeError(
f"Class '{self.__class__.__name__}' must define srcType and dstType."
)
@classmethod
def getName(cls):
return cls.name or cls.__name__
def canConvert(self, srcType, dstType):
""" Check if this converter corresponds to a source/destination attribute pair.
"""
return isinstance(srcType, self.srcType) and isinstance(dstType, self.dstType)
@abstractmethod
def convert(self, value):
""" Convert a value from the source attribute's type to a value for
the destination attribute's type.
"""
return value
def __repr__(self):
return f"<AttributeConverter {self.getName()} ({self.srcType.__name__} -> {self.dstType.__name__})>"
class AttributeConverterRegistry:
"""
Registry of available converters
"""
# { (srcType, dstType): [converters] }
_converters: dict[tuple["Attribute", "Attribute"], list[AttributeConverter]] = defaultdict(list)
@classmethod
def add(cls, converter: AttributeConverter):
if not issubclass(converter.__class__, AttributeConverter):
raise TypeError(f"{converter} parent class must subclass AttributeConverter")
logging.info(
f"Add converter class: {converter.getName()} "
f"({converter.srcType.__name__} -> {converter.dstType.__name__})"
)
cls._converters[(converter.srcType.__name__, converter.dstType.__name__)].append(converter)
@classmethod
def getAllConverters(cls) -> list[AttributeConverter]:
return list(chain.from_iterable(cls._converters.values()))
@classmethod
def getConverterByName(cls, name):
for c in cls.getAllConverters():
if c.getName() == name:
return c
return None
@classmethod
def hasConverter(cls, srcType: "Attribute", dstType: "Attribute") -> list[AttributeConverter]:
return ((srcType, dstType)) in cls._converters
@classmethod
def getConverters(cls, srcType: "Attribute", dstType: "Attribute") -> list[AttributeConverter]:
""" Get priority-ordered converters.
"""
converters = cls._converters.get((srcType, dstType), [])
return sorted(converters, key=lambda c: -c.priority)
@classmethod
def getConverter(cls, srcType: "Attribute", dstType: "Attribute") -> AttributeConverter:
""" Get highest priority converter. """
converters = cls.getConverters(srcType, dstType)
if not converters:
return None
return converters[0]