Advertisement
Thoughtcoder411

Nft script

Jun 13th, 2024
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.72 KB | Source Code | 0 0
  1. import os
  2. import sys
  3. import json
  4. import random
  5. import argparse
  6. import getpass
  7. import numpy as np
  8. import matplotlib.pyplot as plt
  9. from PIL import Image, ImageDraw, ImageFont
  10. from tqdm import tqdm
  11.  
  12. # Check for required packages
  13. required_packages = ['matplotlib', 'PIL', 'tqdm']
  14. missing_packages = []
  15.  
  16. for package in required_packages:
  17.     try:
  18.         __import__(package)
  19.     except ImportError:
  20.         missing_packages.append(package)
  21.  
  22. if missing_packages:
  23.     print(f"Missing packages: {', '.join(missing_packages)}. Please install them using pip:")
  24.     print(f"pip install {' '.join(missing_packages)}")
  25.     sys.exit(1)
  26.  
  27. # Function to generate a random color
  28. def random_color():
  29.     return (random.random(), random.random(), random.random())
  30.  
  31. # Function to generate random shapes with patterns and materials within sections
  32. def generate_shapes(num_shapes, num_layers, materials, sections):
  33.     shapes = []
  34.     for section in sections:
  35.         x_min, x_max, y_min, y_max = section
  36.         for _ in range(num_shapes):
  37.             for _ in range(num_layers):
  38.                 shape_type = random.choice(['circle', 'square', 'triangle'])
  39.                 size = random.uniform(0.05, 0.3)
  40.                 x = random.uniform(x_min, x_max)
  41.                 y = random.uniform(y_min, y_max)
  42.                 color = random_color()
  43.                 pattern = random.choice(['none', 'splash', 'splatter', 'dripping'])
  44.                 material = random.choice(materials)
  45.                 orientation = random.uniform(0, 360)  # Adding orientation for variation
  46.                 shapes.append((shape_type, x, y, size, color, pattern, material, orientation))
  47.     return shapes
  48.  
  49. # Function to plot shapes within sections
  50. def plot_shapes(shapes, filename, dpi=300, background_color=(1, 1, 1)):
  51.     fig, ax = plt.subplots()
  52.     fig.patch.set_facecolor(background_color)
  53.     for shape in shapes:
  54.         shape_type, x, y, size, color, pattern, material, orientation = shape
  55.         if shape_type == 'circle':
  56.             circle = plt.Circle((x, y), size/2, color=color, label=material)
  57.             ax.add_artist(circle)
  58.         elif shape_type == 'square':
  59.             square = plt.Rectangle((x-size/2, y-size/2), size, size, color=color, label=material, angle=orientation)
  60.             ax.add_artist(square)
  61.         elif shape_type == 'triangle':
  62.             triangle = plt.Polygon([(x, y), (x+size/2, y-size), (x-size/2, y-size)], color=color, label=material)
  63.             t = plt.gca().transData
  64.             coords = [(x, y), (x+size/2, y-size), (x-size/2, y-size)]
  65.             coords_rotated = [(coord[0]*np.cos(np.radians(orientation)) - coord[1]*np.sin(np.radians(orientation)),
  66.                                coord[0]*np.sin(np.radians(orientation)) + coord[1]*np.cos(np.radians(orientation))) for coord in coords]
  67.             triangle = plt.Polygon(coords_rotated, color=color, label=material)
  68.             ax.add_artist(triangle)
  69.         if pattern == 'splash':
  70.             for _ in range(5):
  71.                 splash_x = x + random.uniform(-size, size)
  72.                 splash_y = y + random.uniform(-size, size)
  73.                 splash_size = random.uniform(0.01, size/2)
  74.                 splash = plt.Circle((splash_x, splash_y), splash_size, color=color, alpha=0.5)
  75.                 ax.add_artist(splash)
  76.         elif pattern == 'splatter':
  77.             for _ in range(10):
  78.                 splatter_x = x + random.uniform(-size, size)
  79.                 splatter_y = y + random.uniform(-size, size)
  80.                 splatter_size = random.uniform(0.01, size/3)
  81.                 splatter = plt.Circle((splatter_x, splatter_y), splatter_size, color=color, alpha=0.5)
  82.                 ax.add_artist(splatter)
  83.         elif pattern == 'dripping':
  84.             for _ in range(3):
  85.                 drip_x = x + random.uniform(-size/2, size/2)
  86.                 drip_y = y - size/2
  87.                 drip_length = random.uniform(size/2, size)
  88.                 drip = plt.Line2D([drip_x, drip_x], [drip_y, drip_y - drip_length], color=color, linewidth=2)
  89.                 ax.add_artist(drip)
  90.     ax.set_xlim(0, 1)
  91.     ax.set_ylim(0, 1)
  92.     ax.set_aspect('equal')
  93.     plt.axis('off')
  94.     plt.savefig(filename, dpi=dpi)
  95.     plt.close()
  96.  
  97. # Function to embed metadata into image
  98. def embed_metadata(image_path, metadata):
  99.     with Image.open(image_path) as img:
  100.         draw = ImageDraw.Draw(img)
  101.         metadata_text = json.dumps(metadata, indent=4)
  102.         font = ImageFont.load_default()
  103.         text_x, text_y = 10, img.height - 10 - (len(metadata_text.split('\n')) * 10)
  104.         draw.text((text_x, text_y), metadata_text, (255, 255, 255), font=font)
  105.         img.save(image_path)
  106.  
  107. # Function to generate metadata
  108. def generate_metadata(image_id, shapes, collection_desc, output_dir, collection_name, unique_signature, attributes):
  109.     metadata = {
  110.         "name": f"{collection_name} - NFT Image {image_id}",
  111.         "description": collection_desc,
  112.         "image": f"{output_dir}/nft_image_{image_id}.png",
  113.         "attributes": [],
  114.         "unique_signature": unique_signature,
  115.         "id": image_id
  116.     }
  117.     for shape in shapes:
  118.         shape_type, x, y, size, color, pattern, material, orientation = shape
  119.         metadata["attributes"].append({
  120.             "trait_type": "Shape",
  121.             "value": shape_type
  122.         })
  123.         metadata["attributes"].append({
  124.             "trait_type": "Position",
  125.             "value": {"x": x, "y": y}
  126.         })
  127.         metadata["attributes"].append({
  128.             "trait_type": "Size",
  129.             "value": size
  130.         })
  131.         metadata["attributes"].append({
  132.             "trait_type": "Color",
  133.             "value": {"r": color[0], "g": color[1], "b": color[2]}
  134.         })
  135.         metadata["attributes"].append({
  136.             "trait_type": "Pattern",
  137.             "value": pattern
  138.         })
  139.         metadata["attributes"].append({
  140.             "trait_type": "Material",
  141.             "value": material
  142.         })
  143.         metadata["attributes"].append({
  144.             "trait_type": "Orientation",
  145.             "value": orientation
  146.         })
  147.     # Add custom attributes
  148.     metadata["attributes"].extend(attributes)
  149.     return metadata
  150.  
  151. # User registration and login system
  152. def register_user():
  153.     users = {}
  154.     if os.path.exists("users.json"):
  155.         with open("users.json", "r") as f:
  156.             users = json.load(f)
  157.  
  158.     username = input("Enter a username to register: ")
  159.     if username in users:
  160.         print("Username already exists. Please try again.")
  161.         sys.exit(1)
  162.    
  163.     password = getpass.getpass("Enter a password: ")
  164.     users[username] = password
  165.  
  166.     with open("users.json", "w") as f:
  167.         json.dump(users, f)
  168.  
  169.     print("User registered successfully. Please log in to continue.")
  170.     sys.exit(0)
  171.  
  172. def login_user():
  173.     users = {}
  174.     if os.path.exists("users.json"):
  175.         with open("users.json", "r") as f:
  176.             users = json.load(f)
  177.     else:
  178.         print("No users registered. Please register first.")
  179.         sys.exit(1)
  180.  
  181.     username = input("Enter your username: ")
  182.     if username not in users:
  183.         print("Username not found. Please register first.")
  184.         sys.exit(1)
  185.    
  186.     password = getpass.getpass("Enter your password: ")
  187.     if users[username] != password:
  188.         print("Incorrect password. Please try again.")
  189.         sys.exit(1)
  190.  
  191.     print("Login successful.")
  192.     return username
  193.  
  194. # Function to generate sections based on the number of sections specified by the user
  195. def generate_sections(num_sections):
  196.     rows = int(np.ceil(np.sqrt(num_sections)))
  197.     cols = rows
  198.     section_width = 1.0 / cols
  199.     section_height = 1.0 / rows
  200.     sections = []
  201.     for i in range(rows):
  202.         for j in range(cols):
  203.             if len(sections) < num_sections:
  204.                 x_min = j * section_width
  205.                 x_max = x_min + section_width
  206.                 y_min = i * section_height
  207.                 y_max = y_min + section_height
  208.                 sections.append((x_min, x_max, y_min, y_max))
  209.     return sections
  210.  
  211. # Function to ask user for NFT details interactively
  212. def get_nft_details():
  213.     num_nfts = int(input("How many NFTs do you want to create? "))
  214.     collection_name = input("Enter the name of the NFT collection: ")
  215.     collection_desc = input("Enter the description of the NFT collection: ")
  216.     unique_signature = input("Enter a unique signature for the NFT collection: ")
  217.     image_quality = input("Enter the image quality in DPI (default: 300): ")
  218.     image_quality = int(image_quality) if image_quality else 300
  219.     num_layers = input("Enter the number of layers for each NFT (default: 1): ")
  220.     num_layers = int(num_layers) if num_layers else 1
  221.     background_color_input = input("Enter the background color (r,g,b) (default: 1,1,1): ")
  222.     if background_color_input:
  223.         background_color = tuple(map(float, background_color_input.split(',')))
  224.     else:
  225.         background_color = (1, 1, 1)
  226.     materials_input = input("Enter the materials (comma-separated) (default: paper,wood,metal,glass): ")
  227.     if materials_input:
  228.         materials = materials_input.split(',')
  229.     else:
  230.         materials = ["paper", "wood", "metal", "glass"]
  231.     custom_attributes_input = input("Enter custom attributes (key:value, comma-separated): ")
  232.     custom_attributes = dict(attr.split(':') for attr in custom_attributes_input.split(',')) if custom_attributes_input else {}
  233.  
  234.     num_sections = int(input("How many sections do you want to divide the image into? "))
  235.     sections = generate_sections(num_sections)
  236.  
  237.     return num_nfts, collection_name, collection_desc, unique_signature, image_quality, num_layers, background_color, materials, custom_attributes, sections
  238.  
  239. # Main function to create NFTs
  240. def create_nfts(num_nfts, collection_name, collection_desc, unique_signature, image_quality, num_layers, background_color, materials, custom_attributes, sections):
  241.     print(f"Creating the collection '{collection_name}' of {num_nfts} NFTs.")
  242.    
  243.     # Create the main directory
  244.     main_dir = collection_name.replace(" ", "_")
  245.     if not os.path.exists(main_dir):
  246.         os.makedirs(main_dir)
  247.     print(f"Created main directory: {main_dir}")
  248.  
  249.     for i in range(num_nfts):
  250.         print(f"Creating NFT {i+1}/{num_nfts} with {num_layers} layers...")
  251.        
  252.         # Create a subdirectory for each NFT
  253.         nft_dir = os.path.join(main_dir, f"nft_{i+1}")
  254.         if not os.path.exists(nft_dir):
  255.             os.makedirs(nft_dir)
  256.         print(f"Created directory for NFT {i+1}: {nft_dir}")
  257.  
  258.         # Initialize the progress bar
  259.         with tqdm(total=100, desc=f"Creating NFT {i+1}", bar_format="{l_bar}{bar} [ time left: {remaining} ]") as pbar:
  260.            
  261.             # Generate shapes and plot the image
  262.             shapes = generate_shapes(random.randint(5, 15), num_layers, materials, sections)
  263.             image_path = os.path.join(nft_dir, f"nft_image_{i+1}.png")
  264.             plot_shapes(shapes, image_path, dpi=image_quality, background_color=background_color)
  265.             pbar.update(70)  # Update the progress bar after plotting shapes
  266.             print(f"Generated and saved image: {image_path}")
  267.            
  268.             # Generate metadata and save it
  269.             attributes = [{"trait_type": k, "value": v} for k, v in custom_attributes.items()]
  270.             metadata = generate_metadata(i+1, shapes, collection_desc, nft_dir, collection_name, unique_signature, attributes)
  271.             metadata_path = os.path.join(nft_dir, f'nft_metadata_{i+1}.json')
  272.             with open(metadata_path, 'w') as f:
  273.                 json.dump(metadata, f, indent=4)
  274.             pbar.update(20)  # Update the progress bar after generating metadata
  275.             print(f"Generated and saved metadata: {metadata_path}")
  276.            
  277.             # Embed metadata into the image
  278.             embed_metadata(image_path, metadata)
  279.             pbar.update(10)  # Update the progress bar after embedding metadata
  280.             print(f"Embedded metadata into image: {image_path}")
  281.  
  282. # Parse command line arguments
  283. parser = argparse.ArgumentParser(description='Create NFT images and metadata.')
  284. subparsers = parser.add_subparsers(dest='command')
  285.  
  286. # Register user command
  287. register_parser = subparsers.add_parser('register', help='Register a new user')
  288.  
  289. # Login user command
  290. login_parser = subparsers.add_parser('login', help='Login as an existing user')
  291.  
  292. # Create NFTs command
  293. create_parser = subparsers.add_parser('create', help='Create NFT images and metadata')
  294.  
  295. # Cool command to provide detailed usage information
  296. def cool_command():
  297.     print("""
  298.    Usage Instructions:
  299.    -------------------
  300.    This script generates a collection of NFT images with metadata.
  301.  
  302.    Commands:
  303.    ---------
  304.    1. Register a new user:
  305.       python create_nfts.py register
  306.  
  307.    2. Login as an existing user:
  308.       python create_nfts.py login
  309.  
  310.    3. Create a collection with NFTs:
  311.       python create_nfts.py create
  312.  
  313.    Examples:
  314.    ---------
  315.    1. Register a new user:
  316.       python create_nfts.py register
  317.  
  318.    2. Login as an existing user:
  319.       python create_nfts.py login
  320.  
  321.    3. Create a collection interactively after logging in:
  322.       python create_nfts.py create
  323.  
  324.    Ensure you have registered and logged in before attempting to create NFTs.
  325.    """)
  326.     sys.exit(0)
  327.  
  328. cool_parser = subparsers.add_parser('cool', help='Show usage instructions and examples')
  329. cool_parser.set_defaults(func=cool_command)
  330.  
  331. args = parser.parse_args()
  332.  
  333. # Handle commands
  334. if args.command == 'register':
  335.     register_user()
  336. elif args.command == 'login':
  337.     login_user()
  338. elif args.command == 'create':
  339.     if login_user():
  340.         details = get_nft_details()
  341.         create_nfts(*details)
  342. elif args.command == 'cool':
  343.     cool_command()
  344. else:
  345.     parser.print_help()
  346.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement