Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import sys
- import json
- import random
- import argparse
- import getpass
- import numpy as np
- import matplotlib.pyplot as plt
- from PIL import Image, ImageDraw, ImageFont
- from tqdm import tqdm
- # Check for required packages
- required_packages = ['matplotlib', 'PIL', 'tqdm']
- missing_packages = []
- for package in required_packages:
- try:
- __import__(package)
- except ImportError:
- missing_packages.append(package)
- if missing_packages:
- print(f"Missing packages: {', '.join(missing_packages)}. Please install them using pip:")
- print(f"pip install {' '.join(missing_packages)}")
- sys.exit(1)
- # Function to generate a random color
- def random_color():
- return (random.random(), random.random(), random.random())
- # Function to generate random shapes with patterns and materials within sections
- def generate_shapes(num_shapes, num_layers, materials, sections):
- shapes = []
- for section in sections:
- x_min, x_max, y_min, y_max = section
- for _ in range(num_shapes):
- for _ in range(num_layers):
- shape_type = random.choice(['circle', 'square', 'triangle'])
- size = random.uniform(0.05, 0.3)
- x = random.uniform(x_min, x_max)
- y = random.uniform(y_min, y_max)
- color = random_color()
- pattern = random.choice(['none', 'splash', 'splatter', 'dripping'])
- material = random.choice(materials)
- orientation = random.uniform(0, 360) # Adding orientation for variation
- shapes.append((shape_type, x, y, size, color, pattern, material, orientation))
- return shapes
- # Function to plot shapes within sections
- def plot_shapes(shapes, filename, dpi=300, background_color=(1, 1, 1)):
- fig, ax = plt.subplots()
- fig.patch.set_facecolor(background_color)
- for shape in shapes:
- shape_type, x, y, size, color, pattern, material, orientation = shape
- if shape_type == 'circle':
- circle = plt.Circle((x, y), size/2, color=color, label=material)
- ax.add_artist(circle)
- elif shape_type == 'square':
- square = plt.Rectangle((x-size/2, y-size/2), size, size, color=color, label=material, angle=orientation)
- ax.add_artist(square)
- elif shape_type == 'triangle':
- triangle = plt.Polygon([(x, y), (x+size/2, y-size), (x-size/2, y-size)], color=color, label=material)
- t = plt.gca().transData
- coords = [(x, y), (x+size/2, y-size), (x-size/2, y-size)]
- coords_rotated = [(coord[0]*np.cos(np.radians(orientation)) - coord[1]*np.sin(np.radians(orientation)),
- coord[0]*np.sin(np.radians(orientation)) + coord[1]*np.cos(np.radians(orientation))) for coord in coords]
- triangle = plt.Polygon(coords_rotated, color=color, label=material)
- ax.add_artist(triangle)
- if pattern == 'splash':
- for _ in range(5):
- splash_x = x + random.uniform(-size, size)
- splash_y = y + random.uniform(-size, size)
- splash_size = random.uniform(0.01, size/2)
- splash = plt.Circle((splash_x, splash_y), splash_size, color=color, alpha=0.5)
- ax.add_artist(splash)
- elif pattern == 'splatter':
- for _ in range(10):
- splatter_x = x + random.uniform(-size, size)
- splatter_y = y + random.uniform(-size, size)
- splatter_size = random.uniform(0.01, size/3)
- splatter = plt.Circle((splatter_x, splatter_y), splatter_size, color=color, alpha=0.5)
- ax.add_artist(splatter)
- elif pattern == 'dripping':
- for _ in range(3):
- drip_x = x + random.uniform(-size/2, size/2)
- drip_y = y - size/2
- drip_length = random.uniform(size/2, size)
- drip = plt.Line2D([drip_x, drip_x], [drip_y, drip_y - drip_length], color=color, linewidth=2)
- ax.add_artist(drip)
- ax.set_xlim(0, 1)
- ax.set_ylim(0, 1)
- ax.set_aspect('equal')
- plt.axis('off')
- plt.savefig(filename, dpi=dpi)
- plt.close()
- # Function to embed metadata into image
- def embed_metadata(image_path, metadata):
- with Image.open(image_path) as img:
- draw = ImageDraw.Draw(img)
- metadata_text = json.dumps(metadata, indent=4)
- font = ImageFont.load_default()
- text_x, text_y = 10, img.height - 10 - (len(metadata_text.split('\n')) * 10)
- draw.text((text_x, text_y), metadata_text, (255, 255, 255), font=font)
- img.save(image_path)
- # Function to generate metadata
- def generate_metadata(image_id, shapes, collection_desc, output_dir, collection_name, unique_signature, attributes):
- metadata = {
- "name": f"{collection_name} - NFT Image {image_id}",
- "description": collection_desc,
- "image": f"{output_dir}/nft_image_{image_id}.png",
- "attributes": [],
- "unique_signature": unique_signature,
- "id": image_id
- }
- for shape in shapes:
- shape_type, x, y, size, color, pattern, material, orientation = shape
- metadata["attributes"].append({
- "trait_type": "Shape",
- "value": shape_type
- })
- metadata["attributes"].append({
- "trait_type": "Position",
- "value": {"x": x, "y": y}
- })
- metadata["attributes"].append({
- "trait_type": "Size",
- "value": size
- })
- metadata["attributes"].append({
- "trait_type": "Color",
- "value": {"r": color[0], "g": color[1], "b": color[2]}
- })
- metadata["attributes"].append({
- "trait_type": "Pattern",
- "value": pattern
- })
- metadata["attributes"].append({
- "trait_type": "Material",
- "value": material
- })
- metadata["attributes"].append({
- "trait_type": "Orientation",
- "value": orientation
- })
- # Add custom attributes
- metadata["attributes"].extend(attributes)
- return metadata
- # User registration and login system
- def register_user():
- users = {}
- if os.path.exists("users.json"):
- with open("users.json", "r") as f:
- users = json.load(f)
- username = input("Enter a username to register: ")
- if username in users:
- print("Username already exists. Please try again.")
- sys.exit(1)
- password = getpass.getpass("Enter a password: ")
- users[username] = password
- with open("users.json", "w") as f:
- json.dump(users, f)
- print("User registered successfully. Please log in to continue.")
- sys.exit(0)
- def login_user():
- users = {}
- if os.path.exists("users.json"):
- with open("users.json", "r") as f:
- users = json.load(f)
- else:
- print("No users registered. Please register first.")
- sys.exit(1)
- username = input("Enter your username: ")
- if username not in users:
- print("Username not found. Please register first.")
- sys.exit(1)
- password = getpass.getpass("Enter your password: ")
- if users[username] != password:
- print("Incorrect password. Please try again.")
- sys.exit(1)
- print("Login successful.")
- return username
- # Function to generate sections based on the number of sections specified by the user
- def generate_sections(num_sections):
- rows = int(np.ceil(np.sqrt(num_sections)))
- cols = rows
- section_width = 1.0 / cols
- section_height = 1.0 / rows
- sections = []
- for i in range(rows):
- for j in range(cols):
- if len(sections) < num_sections:
- x_min = j * section_width
- x_max = x_min + section_width
- y_min = i * section_height
- y_max = y_min + section_height
- sections.append((x_min, x_max, y_min, y_max))
- return sections
- # Function to ask user for NFT details interactively
- def get_nft_details():
- num_nfts = int(input("How many NFTs do you want to create? "))
- collection_name = input("Enter the name of the NFT collection: ")
- collection_desc = input("Enter the description of the NFT collection: ")
- unique_signature = input("Enter a unique signature for the NFT collection: ")
- image_quality = input("Enter the image quality in DPI (default: 300): ")
- image_quality = int(image_quality) if image_quality else 300
- num_layers = input("Enter the number of layers for each NFT (default: 1): ")
- num_layers = int(num_layers) if num_layers else 1
- background_color_input = input("Enter the background color (r,g,b) (default: 1,1,1): ")
- if background_color_input:
- background_color = tuple(map(float, background_color_input.split(',')))
- else:
- background_color = (1, 1, 1)
- materials_input = input("Enter the materials (comma-separated) (default: paper,wood,metal,glass): ")
- if materials_input:
- materials = materials_input.split(',')
- else:
- materials = ["paper", "wood", "metal", "glass"]
- custom_attributes_input = input("Enter custom attributes (key:value, comma-separated): ")
- custom_attributes = dict(attr.split(':') for attr in custom_attributes_input.split(',')) if custom_attributes_input else {}
- num_sections = int(input("How many sections do you want to divide the image into? "))
- sections = generate_sections(num_sections)
- return num_nfts, collection_name, collection_desc, unique_signature, image_quality, num_layers, background_color, materials, custom_attributes, sections
- # Main function to create NFTs
- def create_nfts(num_nfts, collection_name, collection_desc, unique_signature, image_quality, num_layers, background_color, materials, custom_attributes, sections):
- print(f"Creating the collection '{collection_name}' of {num_nfts} NFTs.")
- # Create the main directory
- main_dir = collection_name.replace(" ", "_")
- if not os.path.exists(main_dir):
- os.makedirs(main_dir)
- print(f"Created main directory: {main_dir}")
- for i in range(num_nfts):
- print(f"Creating NFT {i+1}/{num_nfts} with {num_layers} layers...")
- # Create a subdirectory for each NFT
- nft_dir = os.path.join(main_dir, f"nft_{i+1}")
- if not os.path.exists(nft_dir):
- os.makedirs(nft_dir)
- print(f"Created directory for NFT {i+1}: {nft_dir}")
- # Initialize the progress bar
- with tqdm(total=100, desc=f"Creating NFT {i+1}", bar_format="{l_bar}{bar} [ time left: {remaining} ]") as pbar:
- # Generate shapes and plot the image
- shapes = generate_shapes(random.randint(5, 15), num_layers, materials, sections)
- image_path = os.path.join(nft_dir, f"nft_image_{i+1}.png")
- plot_shapes(shapes, image_path, dpi=image_quality, background_color=background_color)
- pbar.update(70) # Update the progress bar after plotting shapes
- print(f"Generated and saved image: {image_path}")
- # Generate metadata and save it
- attributes = [{"trait_type": k, "value": v} for k, v in custom_attributes.items()]
- metadata = generate_metadata(i+1, shapes, collection_desc, nft_dir, collection_name, unique_signature, attributes)
- metadata_path = os.path.join(nft_dir, f'nft_metadata_{i+1}.json')
- with open(metadata_path, 'w') as f:
- json.dump(metadata, f, indent=4)
- pbar.update(20) # Update the progress bar after generating metadata
- print(f"Generated and saved metadata: {metadata_path}")
- # Embed metadata into the image
- embed_metadata(image_path, metadata)
- pbar.update(10) # Update the progress bar after embedding metadata
- print(f"Embedded metadata into image: {image_path}")
- # Parse command line arguments
- parser = argparse.ArgumentParser(description='Create NFT images and metadata.')
- subparsers = parser.add_subparsers(dest='command')
- # Register user command
- register_parser = subparsers.add_parser('register', help='Register a new user')
- # Login user command
- login_parser = subparsers.add_parser('login', help='Login as an existing user')
- # Create NFTs command
- create_parser = subparsers.add_parser('create', help='Create NFT images and metadata')
- # Cool command to provide detailed usage information
- def cool_command():
- print("""
- Usage Instructions:
- -------------------
- This script generates a collection of NFT images with metadata.
- Commands:
- ---------
- 1. Register a new user:
- python create_nfts.py register
- 2. Login as an existing user:
- python create_nfts.py login
- 3. Create a collection with NFTs:
- python create_nfts.py create
- Examples:
- ---------
- 1. Register a new user:
- python create_nfts.py register
- 2. Login as an existing user:
- python create_nfts.py login
- 3. Create a collection interactively after logging in:
- python create_nfts.py create
- Ensure you have registered and logged in before attempting to create NFTs.
- """)
- sys.exit(0)
- cool_parser = subparsers.add_parser('cool', help='Show usage instructions and examples')
- cool_parser.set_defaults(func=cool_command)
- args = parser.parse_args()
- # Handle commands
- if args.command == 'register':
- register_user()
- elif args.command == 'login':
- login_user()
- elif args.command == 'create':
- if login_user():
- details = get_nft_details()
- create_nfts(*details)
- elif args.command == 'cool':
- cool_command()
- else:
- parser.print_help()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement