Skip to content

Commit

Permalink
Merge pull request #63 from Jon-Becker/jon-becker/float-validation
Browse files Browse the repository at this point in the history
fix(validation): ensure values, filename, and weights are consistent
  • Loading branch information
Jon-Becker committed Apr 12, 2024
2 parents f96e9df + 566742b commit b9a011c
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 109 deletions.
21 changes: 0 additions & 21 deletions .github/workflows/safety-check.yaml

This file was deleted.

2 changes: 2 additions & 0 deletions .github/workflows/tests-merged.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ name: Unit Tests (on PR)
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

permissions:
contents: read
Expand Down
62 changes: 0 additions & 62 deletions .github/workflows/tests.yaml

This file was deleted.

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
60 changes: 60 additions & 0 deletions tests/test_validate_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,66 @@ def test_validate_config_missing_key():
validate_config(config)


def test_validate_config_layer_mismatch_weights():
config = {
"layers": [
{
"name": "Background",
"values": ["Python Logo", "some other value"],
"trait_path": "./trait-layers/foreground",
"filename": ["logo", "some file"],
"weights": [100],
}
],
"baseURI": ".",
"name": "NFT #",
"description": "This is a description for this NFT series.",
}

with pytest.raises(ConfigValidationError):
validate_config(config)


def test_validate_config_layer_mismatch_filename():
config = {
"layers": [
{
"name": "Background",
"values": ["Python Logo", "some other value"],
"trait_path": "./trait-layers/foreground",
"filename": ["logo"],
"weights": [100, 100],
}
],
"baseURI": ".",
"name": "NFT #",
"description": "This is a description for this NFT series.",
}

with pytest.raises(ConfigValidationError):
validate_config(config)


def test_validate_config_layer_mismatch_values():
config = {
"layers": [
{
"name": "Background",
"values": ["Python Logo"],
"trait_path": "./trait-layers/foreground",
"filename": ["logo", "logo 2"],
"weights": [100, 100],
}
],
"baseURI": ".",
"name": "NFT #",
"description": "This is a description for this NFT series.",
}

with pytest.raises(ConfigValidationError):
validate_config(config)


def test_validate_config_incorrect_type():
config = {
"layers": "should be a list",
Expand Down

0 comments on commit b9a011c

Please sign in to comment.