-
Notifications
You must be signed in to change notification settings - Fork 562
/
Copy pathservice_customization_helpers.py
1216 lines (984 loc) · 47.2 KB
/
service_customization_helpers.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2023 Boston Dynamics, Inc. All rights reserved.
#
# Downloading, reproducing, distributing or otherwise using the SDK Software
# is subject to the terms and conditions of the Boston Dynamics Software
# Development Kit License (20191101-BDSDK-SL).
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Optional, Union
from bosdyn.api.image_geometry_pb2 import AreaI
from bosdyn.api.service_customization_pb2 import (BoolParam, CustomParam, CustomParamError,
DictParam, DoubleParam, Int64Param, ListParam,
OneOfParam, RegionOfInterestParam, StringParam,
UserInterfaceInfo)
from bosdyn.api.units_pb2 import Units
class InvalidCustomParamSpecError(ValueError):
"""Error indicating that the defined custom parameter Spec is invalid,
with a list of error messages explaining why the spec is invalid"""
class InvalidCustomParamValueError(ValueError):
"""Error indicating that the defined custom parameter value does not match
the associated Spec, with a list of error messages explaining why."""
def __init__(self, proto_error: CustomParamError):
self.proto_error = proto_error
def validate_dict_spec(dict_spec: DictParam.Spec) -> None:
"""
Checks that a DictParam.Spec is valid
Args:
dict_spec (service_customization_pb2.DictParam.Spec): Spec to be validated
Returns:
None for a valid spec
Raises:
InvalidCustomParamSpecError with a list of error messages for invalid specs.
"""
return _DictParamValidator(dict_spec).validate_spec()
def create_value_validator(
dict_spec: DictParam.Spec) -> Callable[[DictParam], Optional[CustomParamError]]:
"""
Checks if the DictParam.Spec is value and if so, returns a function that can be used to validate any DictParam value
Args:
dict_spec (service_customization_pb2.DictParam.Spec): Spec to be validated and validate values against
Raises:
InvalidCustomParamSpecError with a list of error messages if the dict_spec is invalid
Returns:
A validate_value function that can be called on any value to verify it against this Spec.
The returned function will itself return None if called on a valid value, and a CustomParamError
with a status besides STATUS_OK for an invalid spec
"""
validator = _DictParamValidator(dict_spec)
# Raises an error if the Spec itself is invalid
validator.validate_spec()
return validator.validate_value
def dict_params_to_dict(dict_param: DictParam, dict_spec: DictParam.Spec,
validate: bool = True) -> Dict:
if validate:
validator = create_value_validator(dict_spec)
validate_res = validator(dict_param)
if validate_res:
raise InvalidCustomParamValueError(validate_res)
values = {}
for (key, custom_param) in dict_param.values.items():
value_field = custom_param.WhichOneof("value")
spec_field = dict_spec.specs[key].spec.WhichOneof("spec")
param_value = getattr(custom_param, value_field)
param_spec = getattr(dict_spec.specs[key].spec, spec_field)
if value_field == 'dict_value':
values[key] = dict_params_to_dict(param_value, param_spec, validate=False)
elif value_field == 'list_value':
values[key] = list_params_to_list(param_value, param_spec, validate=False)
elif value_field == 'one_of_value':
values[key] = oneof_param_to_dict(param_value, param_spec, validate=False)
elif value_field == 'roi_value':
values[key] = param_value
elif value_field in ['int_value', 'double_value', 'string_value', 'bool_value']:
values[key] = param_value.value
else:
raise NotImplementedError(
f'No handler for conversion of {value_field} from dict members.')
return values
def list_params_to_list(list_param: ListParam, list_spec: ListParam.Spec,
validate: bool = True) -> List:
if validate:
validator = _ListParamValidator(list_spec)
validator.validate_spec()
validate_res = validator.validate_value(list_param)
if validate_res:
raise InvalidCustomParamValueError(validate_res)
values = []
for (ind, custom_param) in enumerate(list_param.values):
value_field = custom_param.WhichOneof("value")
spec_field = list_spec.element_spec.WhichOneof("spec")
param_value = getattr(custom_param, value_field)
param_spec = getattr(list_spec.element_spec, spec_field)
if value_field == 'dict_value':
values.append(dict_params_to_dict(param_value, param_spec, validate=False))
elif value_field == 'list_value':
values.append(list_params_to_list(param_value, param_spec, validate=False))
elif value_field == 'one_of_value':
values.append(oneof_param_to_dict(param_value, param_spec, validate=False))
elif value_field == 'roi_value':
values.append(param_value)
elif value_field in ['int_value', 'double_value', 'string_value', 'bool_value']:
values.append(param_value.value)
else:
raise NotImplementedError(
f'No handler for conversion of {value_field} from list members.')
return values
def oneof_param_to_dict(oneof_param: OneOfParam, oneof_spec: OneOfParam.Spec,
validate: bool = True) -> Dict:
if validate:
validator = _OneOfParamValidator(oneof_spec)
validator.validate_spec()
validate_res = validator.validate_value(oneof_param)
if validate_res:
raise InvalidCustomParamValueError(validate_res)
dict_param = oneof_param.values[oneof_param.key]
dict_spec = oneof_spec.specs[oneof_param.key].spec
return dict_params_to_dict(dict_param, dict_spec)
def check_types_match(param, proto_type):
if type(param) != proto_type:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE,
error_messages=[
f"Param {param} has type {type(param)}" \
f" but the spec requires {proto_type}."
])
return None
class _ParamValidatorInterface(ABC):
""" Class providing a common structure and interface to validate parameter types.
Specifically, a <Type>ParamValidator class can be used to validate a service_customization_pb2.<Type>Param.Spec
via a validate_spec function with a consistent signature, and can validate a service_customization_pb2.<Type>Param
against a specific Spec via a validate_value function
Args:
param_spec (service_customization_pb2.<Type>Param.Spec): A Spec message for a type of custom parameter
"""
@abstractmethod
def __init__(self, param_spec):
self.param_spec = param_spec
@abstractmethod
def validate_spec(self) -> None:
"""
Checks if the parameter Spec is valid for its type
Returns:
None for a valid spec, and raises a CustomParamError with a status besides STATUS_OK for an invalid spec
"""
@abstractmethod
def validate_value(self, param_value) -> Optional[CustomParamError]:
"""
Checks if a parameter value is valid for this class's self.param_spec
Args:
param_value (service_customization.<Type>Param): A custom parameter value to validate against self.param_spec
Returns:
None for a valid value, and returns a service_customization_pb2.CustomParamError with a status besides STATUS_OK for an invalid value
"""
class _DictParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.DictParam.Spec
Args:
param_spec (service_customization_pb2.DictParam.Spec): The DictParam Spec this helper instance is being used for
"""
proto_type = DictParam
custom_param_value_field = "dict_value"
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
custom_param_error = CustomParamError(status=CustomParamError.STATUS_OK)
error_list = []
for name, child_spec in self.param_spec.specs.items():
try:
_CustomParamValidator(child_spec.spec).get_param_helper().validate_spec()
except InvalidCustomParamSpecError as e:
error_list.extend(_nested_error_message_helper(name, e.args[0]))
if error_list:
raise InvalidCustomParamSpecError(error_list)
def validate_value(self, param_value):
"""
Checks if a parameter value is valid for this class's self.param_spec
Args:
param_value (service_customization.DictParam): A custom parameter value to validate against self.param_spec
Returns:
Nothing for a valid spec, and raises a service_customization_pb2.CustomParamError for an invalid Spec.
"""
err = check_types_match(param_value, self.proto_type)
if err:
return err
value_keys = set(param_value.values.keys())
spec_keys = set(self.param_spec.specs.keys())
if not value_keys.issubset(spec_keys):
return CustomParamError(
status=CustomParamError.STATUS_UNSUPPORTED_PARAMETER, error_messages=[
f"DictParam value contains keys {value_keys - spec_keys} not present in the spec."
])
custom_param_error = CustomParamError(status=CustomParamError.STATUS_OK)
for name, custom_param in param_value.values.items():
child_spec = self.param_spec.specs[name].spec
child_value = getattr(custom_param, custom_param.WhichOneof("value"))
error_proto = _CustomParamValidator(child_spec).get_param_helper().validate_value(
child_value)
if error_proto:
custom_param_error.status = error_proto.status
custom_param_error.error_messages.extend(
_nested_error_message_helper(name, error_proto.error_messages))
if custom_param_error.status != CustomParamError.STATUS_OK:
return custom_param_error
class _NumericalParamValidator(_ParamValidatorInterface):
"""
Generic ParamValidator class for shared logic between numerical Param Specs
Args:
param_spec (service_customization_pb2.<Numerical>Param.Spec): The Numerical Spec this helper instance is being used for
"""
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
error_messages = []
if self.param_spec.HasField("min_value"):
if self.param_spec.min_value.value > self.param_spec.default_value.value:
error_messages.append("Default Spec Value below allowed minimum Value")
if self.param_spec.HasField("max_value"):
if self.param_spec.max_value.value < self.param_spec.default_value.value:
error_messages.append("Default Spec Value above allowed maximum value")
if self.param_spec.HasField("min_value") and self.param_spec.HasField("max_value"):
if self.param_spec.min_value.value > self.param_spec.max_value.value:
error_messages.append("min_value greater than max_value")
if error_messages:
raise InvalidCustomParamSpecError(error_messages)
def validate_value(self, param_value):
err = check_types_match(param_value, self.proto_type)
if err:
return err
num_value = param_value.value
if self.param_spec.HasField("min_value"):
if num_value < self.param_spec.min_value.value:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE, error_messages=[
f"Value {num_value} below min_bound {self.param_spec.min_value.value}"
])
if self.param_spec.HasField("max_value"):
if num_value > self.param_spec.max_value.value:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE, error_messages=[
f"Value {num_value} above max_bound {self.param_spec.max_value.value}"
])
class _Int64ParamValidator(_NumericalParamValidator):
"""
ParamValidator class for a service_customization_pb2.Int64Param.Spec
Args:
param_spec (service_customization_pb2.Int64Param.Spec): The Int64Param Spec this helper instance is being used for
"""
proto_type = Int64Param
custom_param_value_field = "int_value"
def __init__(self, param_spec):
super().__init__(param_spec)
class _DoubleParamValidator(_NumericalParamValidator):
"""
ParamValidator class for a service_customization_pb2.DoubleParam.Spec
Args:
param_spec (service_customization_pb2.DoubleParam.Spec): The DoubleParam Spec this helper instance is being used for
"""
proto_type = DoubleParam
custom_param_value_field = "double_value"
def __init__(self, param_spec):
super().__init__(param_spec)
class _StringParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.StringParam.Spec
Args:
param_spec (service_customization_pb2.StringParam.Spec): The StringParam Spec this helper instance is being used for
"""
proto_type = StringParam
custom_param_value_field = "string_value"
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
if self.param_spec.default_value and not self.param_spec.editable and self.param_spec.options and len(
self.param_spec.options) > 0:
if self.param_spec.default_value not in self.param_spec.options:
raise InvalidCustomParamSpecError([
f"Default string {self.param_spec.default_value} not among options {self.param_spec.options}"
])
def validate_value(self, param_value):
err = check_types_match(param_value, self.proto_type)
if err:
return err
if len(self.param_spec.options) > 0:
if param_value.value not in self.param_spec.options:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE, error_messages=[
f"Chosen string value {param_value.value} not among options {self.param_spec.options}"
])
class _BoolParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.BoolParam.Spec
Args:
param_spec (service_customization_pb2.BoolParam.Spec): The BoolParam Spec this helper instance is being used for
"""
proto_type = BoolParam
custom_param_field = "bool"
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
return super().validate_spec()
def validate_value(self, param_value):
err = check_types_match(param_value, self.proto_type)
if err:
return err
class _RegionOfInterestParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.RegionOfInterestParam.Spec
Args:
param_spec (service_customization_pb2.RegionOfInterestParam.Spec): The RegionOfInterestParam Spec this helper instance is being used for
"""
proto_type = RegionOfInterestParam
custom_param_value_field = "roi_value"
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
if not self.param_spec.allows_rectangle:
if self.param_spec.default_area.rectangle:
raise InvalidCustomParamSpecError(
["Default area is a rectangle despite not being allowed"])
def validate_value(self, param_value):
err = check_types_match(param_value, self.proto_type)
if err:
return err
if not self.param_spec.allows_rectangle:
if param_value.area.rectangle:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE,
error_messages=["Chosen area is a rectangle despite not being allowed"])
if param_value.image_cols < 0:
return CustomParamError(status=CustomParamError.STATUS_INVALID_VALUE,
error_messages=["Number of columns in image must be positive"])
if param_value.image_rows < 0:
return CustomParamError(status=CustomParamError.STATUS_INVALID_VALUE,
error_messages=["Number of rows in image must be positive"])
class _ListParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.ListParam.Spec
Args:
param_spec (service_customization_pb2.ListParam.Spec): The ListParam Spec this helper instance is being used for
"""
proto_type = ListParam
custom_param_value_field = "list_value"
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
# First check element_spec
if not self.param_spec.HasField("element_spec"):
raise InvalidCustomParamSpecError(["ListParam needs a defined element_spec"])
element_spec_error = _CustomParamValidator(
self.param_spec.element_spec).get_param_helper().validate_spec()
if element_spec_error:
raise InvalidCustomParamSpecError(
_nested_error_message_helper("element_spec", element_spec_error.error_messages))
# If that's valid, then check list bounds
error_messages = []
if (
self.param_spec.HasField("min_number_of_values") and
self.param_spec.HasField("max_number_of_values")
) and self.param_spec.min_number_of_values.value > self.param_spec.max_number_of_values.value:
error_messages.append(
f"Max ListParam.Spec size {self.param_spec.max_number_of_values} below minimum size of {self.param_spec.min_number_of_values}"
)
if self.param_spec.max_number_of_values.value < 0 or self.param_spec.min_number_of_values.value < 0:
error_messages.append(
f"Invalid negative list size bound, with (min, max) bound of {(self.param_spec.min_number_of_values.value, self.param_spec.max_number_of_values.value)}"
)
if error_messages:
raise InvalidCustomParamSpecError(error_messages)
def validate_value(self, param_value):
err = check_types_match(param_value, self.proto_type)
if err:
return err
if self.param_spec.HasField("min_number_of_values") and len(
param_value.values) < self.param_spec.min_number_of_values.value:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE, error_messages=[
f"ListParam has {len(param_value.values)} values, which is less than the required minimum {self.param_spec.min_number_of_values}"
])
if self.param_spec.HasField("max_number_of_values") and len(
param_value.values) > self.param_spec.max_number_of_values.value:
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE, error_messages=[
f"ListParam has {len(param_value.values)} values, which is more than the allowed maximum {self.param_spec.max_number_of_values}"
])
custom_param_error = CustomParamError(status=CustomParamError.STATUS_OK)
for custom_param_index in range(len(param_value.values)):
custom_param = param_value.values[custom_param_index]
spec_type = self.param_spec.element_spec.WhichOneof("spec")
value_type = custom_param.WhichOneof("value")
if spec_type.split("_")[0] != value_type.split("_")[0]:
custom_param_error.status = CustomParamError.STATUS_INVALID_TYPE
custom_param_error.error_messages.append(
f"Value is defined as {value_type} at index {custom_param_index} while the List Param Spec expects {spec_type}"
)
continue
custom_param_value = getattr(custom_param, custom_param.WhichOneof("value"))
error_proto = _CustomParamValidator(
self.param_spec.element_spec).get_param_helper().validate_value(custom_param_value)
if error_proto:
custom_param_error.status = error_proto.status
custom_param_error.error_messages.extend(
_nested_error_message_helper(f"[{custom_param_index}]",
error_proto.error_messages))
if custom_param_error.status != CustomParamError.STATUS_OK:
return custom_param_error
class _OneOfParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.OneOfInterestParam.Spec
Args:
param_spec (service_customization_pb2.OneOfInterestParam.Spec): The OneOfInterestParam Spec this helper instance is being used for
"""
proto_type = OneOfParam
custom_param_value_field = "one_of_value"
def __init__(self, param_spec):
super().__init__(param_spec)
def validate_spec(self):
if self.param_spec.default_key and self.param_spec.default_key not in self.param_spec.specs.keys(
):
raise InvalidCustomParamSpecError(
[f"OneOf parameter has nonexistent default key of {self.param_spec.default_key}"])
custom_param_error = CustomParamError(status=CustomParamError.STATUS_OK)
error_list = []
for key, child_spec in self.param_spec.specs.items():
try:
_DictParamValidator(child_spec.spec).validate_spec()
except InvalidCustomParamSpecError as e:
error_list.extend(_nested_error_message_helper(key, e.args[0]))
if error_list:
raise InvalidCustomParamSpecError(error_list)
def validate_value(self, param_value):
err = check_types_match(param_value, self.proto_type)
if err:
return err
if param_value.key not in self.param_spec.specs.keys():
return CustomParamError(
status=CustomParamError.STATUS_INVALID_VALUE,
error_messages=[f"OneOf parameter value has nonexistent key of {param_value.key}"])
# Only check active key since our spec doesn't guarantee valid values at unselected OneOf keys
chosen_param_error = _DictParamValidator(
self.param_spec.specs[param_value.key].spec).validate_value(
param_value.values[param_value.key])
if chosen_param_error:
full_error = CustomParamError(
status=chosen_param_error.status,
error_messages=_nested_error_message_helper(param_value.key,
chosen_param_error.error_messages))
return full_error
class _CustomParamValidator(_ParamValidatorInterface):
"""
ParamValidator class for a service_customization_pb2.CustomParam.Spec
Args:
param_spec (service_customization_pb2.CustomParam.Spec): The CustomParam Spec this helper instance is being used for
"""
custom_param_dict = {
"dict_spec": _DictParamValidator,
"list_spec": _ListParamValidator,
"int_spec": _Int64ParamValidator,
"double_spec": _DoubleParamValidator,
"string_spec": _StringParamValidator,
"roi_spec": _RegionOfInterestParamValidator,
"bool_spec": _BoolParamValidator,
"one_of_spec": _OneOfParamValidator
}
def __init__(self, param_spec):
super().__init__(param_spec)
self.sub_param_helper = self.get_param_helper()
def get_param_helper(self):
"""
Returns the ParamValidator instance for the defined OneOf spec in self.param_spec (a service_customization_pb2.CustomParam.Spec)
"""
field_name = self.param_spec.WhichOneof('spec')
return self.custom_param_dict[field_name](getattr(self.param_spec, field_name))
def validate_spec(self):
return self.sub_param_helper.validate_spec()
def validate_value(self, param_value):
return self.sub_param_helper.validate_value(
getattr(param_value, self.sub_param_helper.custom_param_value_field))
def _nested_error_message_helper(child_name, child_error_messages):
"""
Simple internal string helper function to take a list of errors from a child and return a list of errors
for the parent, with each error specifying which child it came from.
Args:
child_name (string): The human-readable name of the child parameter in the parent's context.
For DictParams and OneOfParams this is the parameter map's key, and for ListParams it's
the index surrounded by brackets, such as "[1]"
child_error_messages (list of strings): List of errors from the child with 'child_name'.
In practice this will likely be copied directly from the "error_messages" field in the
child param's service_customization_pb2.CustomParamError proto
"""
joiner_string = " param has error: "
for message_index, child_error in enumerate(child_error_messages):
# If already nested, add child_name with period delimiter
if joiner_string in child_error:
child_error_messages[message_index] = child_name + "." + child_error
# Else, make into a human-readable nested format
else:
child_error_messages[message_index] = child_name + joiner_string + child_error
# Remove period delimiter for list indices
child_error_messages[message_index] = child_error_messages[message_index].replace(".[", "[")
return child_error_messages
def custom_spec_to_default(spec):
"""
Create a default service_customization_pb2.CustomParam based off of the service_customization_pb2.CustomParam.Spec argument
Args:
spec (service_customization_pb2.CustomParam.Spec): spec to which the parameter should be defaulted
"""
which_spec = spec.WhichOneof('spec')
default_func = _SPEC_VALUES[which_spec][1]
param_value = default_func(getattr(spec, which_spec))
if param_value is None:
return None
if which_spec == 'dict_spec':
return CustomParam(dict_value=param_value)
elif which_spec == 'list_spec':
return CustomParam(list_value=param_value)
elif which_spec == 'int_spec':
return CustomParam(int_value=param_value)
elif which_spec == 'double_spec':
return CustomParam(double_value=param_value)
elif which_spec == 'string_spec':
return CustomParam(string_value=param_value)
elif which_spec == 'roi_spec':
return CustomParam(roi_value=param_value)
elif which_spec == 'bool_spec':
return CustomParam(bool_value=param_value)
elif which_spec == 'one_of_spec':
return CustomParam(one_of_value=param_value)
else:
return None
def dict_spec_to_default(spec):
"""
Create a default service_customization_pb2.DictParam based off of the service_customization_pb2.DictParam.Spec argument.
Args:
spec (service_customization_pb2.DictParam.Spec): spec to which the parameter should be defaulted
"""
param = DictParam()
for (key, value) in spec.specs.items():
default_value_param = custom_spec_to_default(value.spec)
if default_value_param is not None:
param.values[key].CopyFrom(default_value_param)
return param
def list_spec_to_default(spec):
"""
Create a default service_customization_pb2.ListParam based off of the service_customization_pb2.ListParam.Spec argument
Args:
spec (service_customization_pb2.ListParam.Spec): spec to which the parameter should be defaulted
"""
param = ListParam()
default_element_spec = custom_spec_to_default(spec.element_spec)
if default_element_spec is not None:
for i in range(0, spec.min_number_of_values.value):
param.values.append(default_element_spec)
return param
def int_spec_to_default(spec):
"""
Create a default service_customization_pb2.IntParam based off of the service_customization_pb2.IntParam.Spec argument
Args:
spec (service_customization_pb2.IntParam.Spec): spec to which the parameter should be defaulted
"""
param = Int64Param()
if spec.HasField('default_value'):
param.value = spec.default_value.value
elif spec.HasField('min_value'):
param.value = spec.min_value.value
elif spec.HasField('max_value'):
param.value = spec.max_value.value
else:
param.value = 0
return param
def double_spec_to_default(spec):
"""
Create a default service_customization_pb2.DoubleParam based off of the service_customization_pb2.DoubleParam.Spec argument
Args:
spec (service_customization_pb2.DoubleParam.Spec): spec to which the parameter should be defaulted
"""
param = DoubleParam()
if spec.HasField('default_value'):
param.value = spec.default_value.value
elif spec.HasField('min_value'):
param.value = spec.min_value.value
elif spec.HasField('max_value'):
param.value = spec.max_value.value
else:
param.value = 0
return param
def string_spec_to_default(spec):
"""
Create a default service_customization_pb2.StringParam based off of the service_customization_pb2.StringParam.Spec argument
Args:
spec (service_customization_pb2.StringParam.Spec): spec to which the parameter should be defaulted
"""
param = StringParam()
if spec.default_value != '':
param.value = spec.default_value
elif len(spec.options) > 0:
param.value = spec.options[0]
else:
param.value = ''
return param
def roi_spec_to_default(spec):
"""
Create a default service_customization_pb2.RegionOfInterestParam based off of the service_customization_pb2.RegionOfInterestParam.Spec argument
Args:
spec (service_customization_pb2.RegionOfInterestParam.Spec): spec to which the parameter should be defaulted
"""
if not spec.allows_rectangle:
return None
param = RegionOfInterestParam()
if spec.HasField('default_area'):
param.area.CopyFrom(spec.default_area)
if spec.HasField('service_and_source'):
param.service_and_source.CopyFrom(spec.service_and_source)
return param
def bool_spec_to_default(spec):
"""
Create a default service_customization_pb2.BoolParam based off of the service_customization_pb2.BoolParam.Spec argument
Args:
spec (service_customization_pb2.BoolParam.Spec): spec to which the parameter should be defaulted
"""
return BoolParam(value=spec.default_value.value)
def one_of_spec_to_default(spec):
"""
Create a default service_customization_pb2.OneOfParam based off of the service_customization_pb2.OneOfParam.Spec argument
Args:
spec (service_customization_pb2.OneOfParam.Spec): spec to which the parameter should be defaulted
"""
param = OneOfParam()
key = spec.default_key
if key not in spec.specs.keys():
return None
param.key = key
for (key, value) in spec.specs.items():
param.values[key].CopyFrom(dict_spec_to_default(value.spec))
return param
def dict_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.DictParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.DictParam): parameter that requires coercing
spec (service_customization_pb2.DictParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
did_coerce = False
new_map = {}
for (key, child_spec) in spec.specs.items():
p = param.values[key]
if p is None:
default_param = custom_spec_to_default(child_spec.spec)
new_map[key] = default_param
did_coerce = True
else:
if custom_param_coerce_to(p, child_spec.spec):
did_coerce = True
new_map[key] = p
param.ClearField('values')
for key in spec.specs.keys():
param.values[key].CopyFrom(new_map[key])
return did_coerce
def list_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.ListParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.ListParam): parameter that requires coercing
spec (service_customization_pb2.ListParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
did_coerce = False
if spec.HasField('min_number_of_values'):
if len(param.values) < spec.min_number_of_values.value:
default_element_param = custom_spec_to_default(spec.element_spec)
param.values.extend(
[default_element_param] * (spec.min_number_of_values.value - len(param.values)))
did_coerce = True
if spec.HasField('max_number_of_values'):
while len(param.values) > spec.max_number_of_values.value:
param.values.pop()
did_coerce = True
for i in range(0, len(param.values)):
if custom_param_coerce_to(param.values[i], spec.element_spec):
did_coerce = True
return did_coerce
def int_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.IntParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.IntParam): parameter that requires coercing
spec (service_customization_pb2.Int.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
invalid_max = spec.HasField('max_value') and param.value > spec.max_value.value
invalid_min = spec.HasField('min_value') and param.value < spec.min_value.value
if invalid_max or invalid_min:
param.Clear()
param.MergeFrom(int_spec_to_default(spec))
return True
return False
def double_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.CustomParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.DoubleParam): parameter that requires coercing
spec (service_customization_pb2.DoubleParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
invalid_max = spec.HasField('max_value') and param.value > spec.max_value.value
invalid_min = spec.HasField('min_value') and param.value < spec.min_value.value
if invalid_max or invalid_min:
param.Clear()
param.MergeFrom(double_spec_to_default(spec))
return True
return False
def string_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.StringParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.StringParam): parameter that requires coercing
spec (service_customization_pb2.StringParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
if not spec.editable and param.value not in spec.options and len(spec.options) > 0:
param.Clear()
param.MergeFrom(string_spec_to_default(spec))
return True
return False
def roi_param_coerce_to(param, spec):
"""
Coercion is tricky with ROI parameters due to the fact that there is no standard frame size. ROI parameter is not
modified in place; rather, a boolean value is returned.
Args:
param (service_customization_pb2.RegionOfInterestParam): parameter that requires coercing
spec (service_customization_pb2.RegionOfInterestParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if service_and_source is unset or if the spec and the parameter match
`False` otherwise
"""
return not spec.HasField(
'service_and_source') or spec.service_and_source == param.service_and_source
def one_of_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.OneOfParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.OneOfParam): parameter that requires coercing
spec (service_customization_pb2.OneOfParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
did_coerce = False
if param.key not in spec.specs.keys():
param.key = sorted(list(spec.specs.keys()))[0]
did_coerce = True
new_map = {}
for (key, child_spec) in spec.specs.items():
value_param = param.values[key]
if value_param is None:
new_map[key] = dict_spec_to_default(child_spec.spec)
did_coerce = True
else:
if dict_param_coerce_to(value_param, child_spec.spec):
did_coerce = True
new_map[key] = value_param
param.ClearField('values')
for key in spec.specs.keys():
param.values[key].CopyFrom(new_map[key])
return did_coerce
_SPEC_VALUES = {
'dict_spec': ('dict_value', dict_spec_to_default, dict_param_coerce_to),
'list_spec': ('list_value', list_spec_to_default, list_param_coerce_to),
'int_spec': ('int_value', int_spec_to_default, int_param_coerce_to),
'double_spec': ('double_value', double_spec_to_default, double_param_coerce_to),
'string_spec': ('string_value', string_spec_to_default, string_param_coerce_to),
'roi_spec': ('roi_value', roi_spec_to_default, roi_param_coerce_to),
'bool_spec':
('bool_value', bool_spec_to_default, None), # No coercing, there are no illegal values.
'one_of_spec': ('one_of_value', one_of_spec_to_default, one_of_param_coerce_to),
}
def custom_param_coerce_to(param, spec):
"""
Coerce a service_customization_pb2.CustomParam based off of the spec passed in. The parameter is modified in-place.
Args:
param (service_customization_pb2.CustomParam): parameter that requires coercing
spec (service_customization_pb2.CustomParam.Spec): spec to which the parameter should be coerced
Returns:
`True` if parameter was coerced
`False` otherwise
"""
did_coerce = False
which_spec = spec.WhichOneof('spec')
field_name, default_value_func, coercion_func = _SPEC_VALUES[which_spec]
if param.HasField(field_name):
if coercion_func is not None:
if coercion_func(getattr(param, field_name), getattr(spec, which_spec)):
did_coerce = True
else:
param.Clear()
getattr(param, field_name).CopyFrom(default_value_func(getattr(spec, which_spec)))
did_coerce = True
return did_coerce
def make_custom_param_spec(