1+ from typing import Self
2+
13from pydantic import BaseModel , ConfigDict , Field
24
35
@@ -8,3 +10,31 @@ class ColorV1(BaseModel):
810 green : int = Field (..., description = "The green value of the color." , ge = 0 , le = 255 )
911 blue : int = Field (..., description = "The blue value of the color." , ge = 0 , le = 255 )
1012 alpha : int = Field (..., description = "The alpha value of the color." , ge = 0 , le = 255 )
13+
14+ @classmethod
15+ def from_list (cls , color : list [int ]) -> Self :
16+ if len (color ) == 3 :
17+ r , g , b = color
18+ a = 255
19+ elif len (color ) == 4 :
20+ r , g , b , a = color
21+ else :
22+ raise ValueError ("Color must be a tuple or list of 3 or 4 integers." )
23+ return cls (red = r , green = g , blue = b , alpha = a )
24+
25+ @classmethod
26+ def from_hex (cls , hex_str : str ) -> Self :
27+ hex_str = hex_str .lstrip ("#" )
28+ if len (hex_str ) == 6 :
29+ r = int (hex_str [0 :2 ], 16 )
30+ g = int (hex_str [2 :4 ], 16 )
31+ b = int (hex_str [4 :6 ], 16 )
32+ a = 255
33+ elif len (hex_str ) == 8 :
34+ r = int (hex_str [0 :2 ], 16 )
35+ g = int (hex_str [2 :4 ], 16 )
36+ b = int (hex_str [4 :6 ], 16 )
37+ a = int (hex_str [6 :8 ], 16 )
38+ else :
39+ raise ValueError ("Hex string must be in the format RRGGBB or RRGGBBAA." )
40+ return cls (red = r , green = g , blue = b , alpha = a )
0 commit comments