Skip to content

Commit

Permalink
fix(validation): ensure values, filename, and weights are consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon-Becker committed Apr 12, 2024
1 parent 626639d commit d5d002c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 26 deletions.
13 changes: 13 additions & 0 deletions src/common/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,19 @@ def validate_config(config: dict) -> bool:
)
)

# ensure each layer["values"] has a corresponding layer["filename"] and layer["weights"]
if len(layer["values"]) != len(layer["filename"]) or len(
layer["values"]
) != len(layer["weights"]):
raise ConfigValidationError(
'config["layers"][{}]: The number of values, filenames, and weights must be the same. Current values: {}, filenames: {}, weights: {}'.format(
i,
len(layer["values"]),
len(layer["filename"]),
len(layer["weights"]),
)
)

# check the incompatibilities and their config values
for i, incompatibility in enumerate(config["incompatibilities"]):
# check if all required incompatibility keys are present
Expand Down
60 changes: 34 additions & 26 deletions src/core/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ def __init__(self, **args):
if not args["config"]:
raise ValueError("No configuration file was provided.")
elif not args["config"].endswith(".json"):
raise ValueError("Invalid configuration file '{}'".format(args["config"]))
raise ValueError(
"Invalid configuration file '{}'".format(args["config"])
)

if not args["amount"]:
raise ValueError("No amount was provided.")
Expand All @@ -40,7 +42,7 @@ def __init__(self, **args):
self.seed = (
int(args["seed"])
if args["seed"] is not None
else int.from_bytes(random.randbytes(16), byteorder='little')
else int.from_bytes(random.randbytes(16), byteorder="little")
)
self.start_at = int(args["start_at"])
self.output = args["output"]
Expand Down Expand Up @@ -124,30 +126,36 @@ def __build_genome_image(self, metadata: dict):
Builds the NFT image for a single NFT.
"""
layers = []
for index, attr in enumerate(metadata["attributes"]):
# get the image for the trait
for i, trait in enumerate(self.config["layers"][index]["values"]):
if trait == attr["value"]:
layers.append(
Image.open(
f'{self.config["layers"][index]["trait_path"]}/{self.config["layers"][index]["filename"][i]}.png'
).convert("RGBA")
)
break

if len(layers) == 1:
rgb_im = layers[0].convert("RGBA")
elif len(layers) == 2:
main_composite = Image.alpha_composite(layers[0], layers[1])
rgb_im = main_composite.convert("RGBA")
elif len(layers) >= 3:
main_composite = Image.alpha_composite(layers[0], layers[1])
for index, remaining in enumerate(layers):
main_composite = Image.alpha_composite(main_composite, remaining)
rgb_im = main_composite.convert("RGBA")

# create folder structure if it doesn't exist
rgb_im.save("{}/images/{}.png".format(self.output, metadata["token_id"]))
try:
for index, attr in enumerate(metadata["attributes"]):
# get the image for the trait
for i, trait in enumerate(self.config["layers"][index]["values"]):
if trait == attr["value"]:
layers.append(
Image.open(
f'{self.config["layers"][index]["trait_path"]}/{self.config["layers"][index]["filename"][i]}.png'
).convert("RGBA")
)
break

if len(layers) == 1:
rgb_im = layers[0].convert("RGBA")
elif len(layers) == 2:
main_composite = Image.alpha_composite(layers[0], layers[1])
rgb_im = main_composite.convert("RGBA")
elif len(layers) >= 3:
main_composite = Image.alpha_composite(layers[0], layers[1])
for index, remaining in enumerate(layers):
main_composite = Image.alpha_composite(main_composite, remaining)
rgb_im = main_composite.convert("RGBA")

# create folder structure if it doesn't exist
rgb_im.save("{}/images/{}.png".format(self.output, metadata["token_id"]))

except Exception as e:
self.logger.error(
"Error generating image for token %d: %s", metadata["token_id"], e
)

def generate(self):
"""
Expand Down

0 comments on commit d5d002c

Please sign in to comment.