from jsonschema import validate from json import dumps, loads from common import convert_color, closest_color, create_colored_image, remove_from_list, closest_color_euclidean, closest_color_weighted_euclidean, euclidean_distance, weighted_euclidean_distance class PalleteSchema : colors = None schema = { "type" : "array", "items" : { "type" : "object", "properties" : { "name" : { "type" : "string" }, "color" : { "type" : "array", "items" : { "type" : "number" } }, "space" : { "type" : "string" } }, "required" : [ "name", "color", "space" ] } } def __init__ (self, file = None, obj = None): if file is not None and obj is None: self.parse_file(file) elif file is not None and obj is not None : self.write(file, obj) else : print('Not sure what you\'re trying to do here') def parse_file (self, file) : with open(file) as f : self.parse(f.read()) print(f'Parsed pallete file {file}') def parse (self, jsonstr) : obj = loads(jsonstr) validate( instance = obj, schema = self.schema) self.colors = obj def write(self, filepath, obj) : validate( instance = obj, schema = self.schema) jsonstr = dumps(obj, indent = 4) with open(filepath, 'w') as outfile : outfile.write(jsonstr) def closest (self, comparison, space = 'BGR', pallete = None) : p = pallete if pallete is not None else self.pallete colors = normalize_colors(space, p) def normalize_colors (self, space = 'BGR', pallete = None) : colors = [] p = pallete if pallete is not None else self.pallete for color in p : colors.append(convert_color(color['color'], color['space'], space)) return colors