Created
April 5, 2024 12:42
-
-
Save jelofsson/2d3baebecefe42f027edf9f0bb6bab30 to your computer and use it in GitHub Desktop.
calculate rarity score - nft-generator-py helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import csv | |
from collections import Counter | |
# | |
# example usage: python3 rarity-score.py | |
# | |
# Load the JSON data | |
with open('./output/metadata/all-objects.json') as f: | |
data = json.load(f) | |
# Count the occurrences of each attribute value per trait type | |
attribute_counts = {} | |
for obj in data: | |
for attribute in obj['attributes']: | |
if attribute['trait_type'] not in attribute_counts: | |
attribute_counts[attribute['trait_type']] = Counter() | |
attribute_counts[attribute['trait_type']][attribute['value']] += 1 | |
# Calculate the rarity score for each object | |
for obj in data: | |
rarity_score = 0 | |
for attribute in obj['attributes']: | |
rarity_score += 1 / attribute_counts[attribute['trait_type']][attribute['value']] | |
obj['rarity_score'] = rarity_score | |
# Sort the objects by rarity score in descending order | |
data.sort(key=lambda obj: obj['rarity_score'], reverse=True) | |
# Write the data to a CSV file | |
with open('rarity_scores.csv', 'w', newline='') as f: | |
writer = csv.writer(f) | |
writer.writerow(['File Number', 'Rarity Score', 'Position']) | |
for i, obj in enumerate(data, start=1): | |
writer.writerow([obj['token_id'], obj['rarity_score'] * 6133, i]) | |
# Calculate the count of each trait and its layer | |
trait_counts = Counter() | |
layer_trait_counts = {} | |
for obj in data: | |
for attribute in obj['attributes']: | |
trait_counts[attribute['value']] += 1 | |
if attribute['trait_type'] not in layer_trait_counts: | |
layer_trait_counts[attribute['trait_type']] = {} | |
if attribute['value'] not in layer_trait_counts[attribute['trait_type']]: | |
layer_trait_counts[attribute['trait_type']][attribute['value']] = 0 | |
layer_trait_counts[attribute['trait_type']][attribute['value']] += 1 | |
# Calculate the total number of traits | |
total_traits = sum(trait_counts.values()) | |
# Write the data to a CSV file | |
with open('rarity_traits.csv', 'w', newline='') as f: | |
writer = csv.writer(f) | |
writer.writerow(['Layer Name', 'Trait Name', 'Count', 'Percentage']) | |
for layer_name, traits in layer_trait_counts.items(): | |
for trait_name, count in traits.items(): | |
percentage = (count / total_traits) * 100 | |
writer.writerow([layer_name, trait_name, count, percentage]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment