labfreed 0.0.3__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
labfreed/validation.py ADDED
@@ -0,0 +1,149 @@
1
+ from pydantic import BaseModel, Field, PrivateAttr
2
+ from typing import List, Set, Tuple
3
+
4
+ from rich import print
5
+ from rich.text import Text
6
+
7
+
8
+ domain_name_pattern = r"(?!-)([A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,63}"
9
+ hsegment_pattern = r"[A-Za-z0-9_\-\.~!$&'()+,:;=@]|%[0-9A-Fa-f]{2}"
10
+
11
+
12
+ class ValidationMessage(BaseModel):
13
+ source:str
14
+ type: str
15
+ problem_msg:str
16
+ recommendation_msg: str = ""
17
+ highlight:str = "" #this can be used to highlight problematic parts
18
+ highlight_sub:list[str] = Field(default_factory=list())
19
+
20
+ @property
21
+ def emphazised_highlight(self):
22
+ fmt = lambda s: f'[emph]{s}[/emph]'
23
+
24
+ if not self.highlight_sub:
25
+ return fmt(self.highlight)
26
+
27
+ result = []
28
+ for c in self.highlight:
29
+ if c in self.highlight_sub:
30
+ result.append(fmt(c))
31
+ else:
32
+ result.append(c)
33
+
34
+ return ''.join(result)
35
+
36
+
37
+ class LabFREEDValidationError(ValueError):
38
+ def __init__(self, message=None, validation_msgs=None):
39
+ super().__init__(message)
40
+ self._validation_msgs = validation_msgs
41
+
42
+ @property
43
+ def validation_msgs(self):
44
+ return self._validation_msgs
45
+
46
+
47
+
48
+
49
+ class BaseModelWithValidationMessages(BaseModel):
50
+ """ Extension of Pydantic BaseModel, so that validator can issue warnings.
51
+ The purpose of that is to allow only minimal validation but on top check for stricter recommendations"""
52
+ _validation_messages: list[ValidationMessage] = PrivateAttr(default_factory=list)
53
+
54
+ def add_validation_message(self, *, msg: str, type:str, recommendation:str="", source:str="", highlight_pattern="", highlight_sub=None):
55
+ if not highlight_sub:
56
+ highlight_sub = []
57
+ w = ValidationMessage(problem_msg=msg, recommendation_msg=recommendation, source=source, type=type, highlight=highlight_pattern, highlight_sub=highlight_sub)
58
+
59
+ if not w in self._validation_messages:
60
+ self._validation_messages.append(w)
61
+
62
+ def get_validation_messages(self) -> list[ValidationMessage]:
63
+ return self._validation_messages
64
+
65
+ def get_errors(self) -> list[ValidationMessage]:
66
+ return filter_errors(self._validation_messages)
67
+
68
+ def get_warnings(self) -> list[ValidationMessage]:
69
+ return filter_warnings(self._validation_messages)
70
+
71
+ def is_valid(self) -> bool:
72
+ return len(filter_errors(self.get_nested_validation_messages())) == 0
73
+
74
+ # Function to extract warnings from a model and its nested models
75
+ def get_nested_validation_messages(self, parent_name: str = "", visited: Set[int] = None) -> List[ValidationMessage]:
76
+ """
77
+ Recursively extract warnings from a Pydantic model and its nested fields.
78
+
79
+ :param model: The Pydantic model instance to inspect.
80
+ :param parent_name: The name of the parent model to track the path.
81
+ :return: List of tuples containing (model name, warning message).
82
+ """
83
+ if visited is None:
84
+ visited = set()
85
+
86
+ model_id = id(self)
87
+ if model_id in visited:
88
+ return []
89
+ visited.add(model_id)
90
+
91
+ warnings_list = [warning for warning in self.get_validation_messages()]
92
+ # warnings_list = [(parent_name or self.__class__.__name__, model_id, warning) for warning in self.get_validation_messages()]
93
+
94
+
95
+ for field_name, field in self.__fields__.items():
96
+ full_path = f"{parent_name}.{field_name}" if parent_name else field_name
97
+ value = getattr(self, field_name)
98
+
99
+ if isinstance(value, BaseModelWithValidationMessages):
100
+ warnings_list.extend(value.get_nested_validation_messages(full_path, visited))
101
+ elif isinstance(value, list):
102
+ for index, item in enumerate(value):
103
+ if isinstance(item, BaseModelWithValidationMessages):
104
+ list_path = f"{full_path}[{index}]"
105
+ warnings_list.extend(item.get_nested_validation_messages(list_path, visited))
106
+ return warnings_list
107
+
108
+
109
+ def get_nested_errors(self) -> list[ValidationMessage]:
110
+ return filter_errors(self.get_nested_validation_messages())
111
+
112
+ def get_nested_warnings(self) -> list[ValidationMessage]:
113
+ return filter_warnings(self.get_nested_validation_messages())
114
+
115
+
116
+ def print_validation_messages(self, str_to_highlight_in=None):
117
+ if not str_to_highlight_in:
118
+ str_to_highlight_in = str(self)
119
+ msgs = self.get_nested_validation_messages()
120
+ print('\n'.join(['\n',
121
+ '=======================================',
122
+ 'Validation Results',
123
+ '---------------------------------------'
124
+ ]
125
+ )
126
+ )
127
+
128
+ for m in msgs:
129
+ if m.type.casefold() == "error":
130
+ color = 'red'
131
+ else:
132
+ color = 'yellow'
133
+
134
+ text = Text.from_markup(f'\n [bold {color}]{m.type} [/bold {color}] in \t {m.source}' )
135
+ print(text)
136
+ formatted_highlight = m.emphazised_highlight.replace('emph', f'bold {color}')
137
+ fmtd = str_to_highlight_in.replace(m.highlight, formatted_highlight)
138
+ fmtd = Text.from_markup(fmtd)
139
+ print(fmtd)
140
+ print(Text.from_markup(f'{m.problem_msg}'))
141
+
142
+
143
+
144
+ def filter_errors(val_msg:list[ValidationMessage]) -> list[ValidationMessage]:
145
+ return [ m for m in val_msg if m.type.casefold() == "error" ]
146
+
147
+ def filter_warnings(val_msg:list[ValidationMessage]) -> list[ValidationMessage]:
148
+ return [ m for m in val_msg if m.type.casefold() != "error" ]
149
+
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.4
2
+ Name: labfreed
3
+ Version: 0.0.3
4
+ Summary: Python implementation of LabFREED building blocks
5
+ Author-email: Reto Thürer <thuerer.r@buchi.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
@@ -0,0 +1,22 @@
1
+ labfreed/__init__.py,sha256=ToYkbhG_8yX4YOS9mieyjvGLG2M8raraqRFDbU71d3A,87
2
+ labfreed/parse_pac.py,sha256=HA3-jAnw2crsXMW_D7Tw-z99qnUWL5MBQVXEzdYP2m4,6287
3
+ labfreed/validation.py,sha256=QwkZWJhAjWbPUZtJJwjVYsw9TxeFhdbZaKjrPPIpuAA,5937
4
+ labfreed/DisplayNameExtension/DisplayNameExtension.py,sha256=l9JZY2eRS0V-H5h3-WXIHiiBJuljns-_e_t9Bp84_CU,1155
5
+ labfreed/PAC_CAT/__init__.py,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2
6
+ labfreed/PAC_CAT/data_model copy.py,sha256=JWMVkwkX9vWZayOLOzdTHk3VZVYBuyupumNqL-cWCxU,9611
7
+ labfreed/PAC_CAT/data_model.py,sha256=pcib1lEQuqejWP7dfmPUtLakz-y-zeDb9CIe94Jmz0A,13677
8
+ labfreed/PAC_ID/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ labfreed/PAC_ID/data_model.py,sha256=g09qgC-TV6fjJw9VyDF6mTJ6co2i2RKZc0Z-BmiiUIQ,7483
10
+ labfreed/PAC_ID/extensions.py,sha256=bvuZnlNKUdwsDLrPm8fyifqPn_PR4wCVkkScFnvRiuM,1158
11
+ labfreed/TREX/UneceUnits.json,sha256=kwfQSp_nTuWbADfBBgqTWrvPl6XtM5SedEVLbMJrM7M,898953
12
+ labfreed/TREX/data_model.py,sha256=_xhnYGMcMPa0uf_020epq88zqHT1wdsUPC2ELJcSRWE,29684
13
+ labfreed/TREX/parse.py,sha256=86962VEJpkrTcT436iFIB5dNed5WHABzpjxRjkA3PXo,2043
14
+ labfreed/TREX/unece_units.py,sha256=scPKdsPzY1neAdFOhA08_tRZaR-yplM8mBhIzzDqZBk,3006
15
+ labfreed/utilities/base36.py,sha256=_yX8aQ1OwrK5tnJU1NUEzQSFGr9xAVnNvPObpNzCPYs,2895
16
+ labfreed/utilities/extension_intertpreters.py,sha256=B3IFJLfVMJQuPfBBtX6ywlDUZEi7_x6tY4g8V7SpWSs,124
17
+ labfreed/utilities/utility_types.py,sha256=Zhk8Mu4hHjkn1gs8oh7vOxxaT7L7wLMVG40ZOWCKGK4,2865
18
+ labfreed/utilities/well_known_keys.py,sha256=nqk66kHdSwJTJfMKlP-xQbBglS8F_NoWsGkfOVITFN0,331
19
+ labfreed-0.0.3.dist-info/licenses/LICENSE,sha256=gHFOv9FRKHxO8cInP3YXyPoJnuNeqrvcHjaE_wPSsQ8,1100
20
+ labfreed-0.0.3.dist-info/WHEEL,sha256=BXjIu84EnBiZ4HkNUBN93Hamt5EPQMQ6VkF7-VZ_Pu0,100
21
+ labfreed-0.0.3.dist-info/METADATA,sha256=c8F4fZqnmeO2IQFSaVItImF2GiT2FPBqWaoRk51EnfM,206
22
+ labfreed-0.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.11.0
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Reto Thürer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.