Skip to content

Commit 478f790

Browse files
committed
feat: img-to-erc721 metadata complete
1 parent 7d14a74 commit 478f790

File tree

5 files changed

+1536
-0
lines changed

5 files changed

+1536
-0
lines changed

erc721/.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.env
2+
/files/

erc721/img-to-erc721.py

+185
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
import base64
2+
import os
3+
import json
4+
from openai import OpenAI
5+
import requests
6+
from dotenv import load_dotenv
7+
from PIL import Image
8+
from PIL import ImageFont
9+
from PIL import ImageDraw
10+
11+
# Load the environment variables from the .env file
12+
load_dotenv()
13+
14+
open_ai_client = OpenAI(
15+
api_key=os.getenv("OPENAI_API_KEY"),
16+
)
17+
18+
src_dir_path = "./files/hellheads"
19+
watermarks_dir_path = "./files/hellheads/watermarks"
20+
thumbnail_extension = "_thumbnail"
21+
22+
ipfs_gateway_url = "https://blockchainassetregistry.infura-ipfs.io/ipfs/"
23+
24+
# Get the values of projectId and projectSecret from the environment variables
25+
infura_project_id = os.getenv("INFURA_PROJECT_ID")
26+
infura_project_secret = os.getenv("INFURA_PROJECT_SECRET")
27+
28+
29+
def encode_image(image_path):
30+
with open(image_path, "rb") as image_file:
31+
return base64.b64encode(image_file.read()).decode("utf-8")
32+
33+
34+
def create_img_thumbnails():
35+
# Loop through each file in the directory
36+
for filename in os.listdir(src_dir_path):
37+
# Check if the file is an image file
38+
if filename.lower().endswith(".png") or filename.lower().endswith(".jpg"):
39+
# Open an image file
40+
file_path = os.path.join(src_dir_path, filename)
41+
with Image.open(file_path) as img:
42+
# Specify the size of the thumbnail
43+
size = (187, 187)
44+
img.thumbnail(size)
45+
# get the file extension
46+
file_extension = filename.split(".")[-1]
47+
# change the file name to include _thumbnail
48+
filename = (
49+
filename.split(".")[0] + thumbnail_extension + "." + file_extension
50+
)
51+
# Save the thumbnail
52+
img.save(os.path.join(src_dir_path, filename))
53+
54+
55+
def add_image_watermark():
56+
# Loop through each file in the directory
57+
for filename in os.listdir(src_dir_path):
58+
# Check if the file is an image file
59+
if filename.lower().endswith(".png") or filename.lower().endswith(".jpg"):
60+
print(f"add_image_watermark: {filename}")
61+
# Open an image file
62+
file_path = os.path.join(src_dir_path, filename)
63+
with Image.open(file_path) as img:
64+
draw = ImageDraw.Draw(img)
65+
w, h = img.size
66+
font_size = int(w * 0.02)
67+
x, y = w - font_size * 4, h - font_size * 4
68+
font = ImageFont.truetype("PPNeueMachina-InktrapRegular.otf", font_size)
69+
draw.text(
70+
(x, y), "@larskristo", fill=(64, 64, 74), font=font, anchor="ms"
71+
)
72+
img.save(os.path.join(watermarks_dir_path, filename))
73+
74+
75+
def upload_file_to_ipfs(file_path):
76+
print(f"upload_to_ipfs: {file_path}")
77+
78+
# Read the file as binary data
79+
with open(file_path, "rb") as file:
80+
file_data = file.read()
81+
82+
# Create the IPFS upload API endpoint URL
83+
endpoint_url = "https://ipfs.infura.io:5001/api/v0/add"
84+
85+
# Set the request parameters
86+
params = {"pin": "true"} # Pin the uploaded file to ensure it is not removed
87+
88+
# Send the POST request to upload the file
89+
response = requests.post(
90+
endpoint_url,
91+
params=params,
92+
files={"file": file_data},
93+
auth=(infura_project_id, infura_project_secret),
94+
)
95+
96+
# Check if the request was successful
97+
if response.status_code == 200:
98+
# Extract the IPFS hash from the response
99+
ipfs_hash = response.json()["Hash"]
100+
return ipfs_hash
101+
else:
102+
# Handle the error case
103+
print(f"Failed to upload file to IPFS. Error: {response.text}")
104+
return None
105+
106+
107+
def get_image_description(image_url):
108+
print(f"get_image_description: {image_url}")
109+
110+
response = open_ai_client.chat.completions.create(
111+
model="gpt-4-vision-preview",
112+
messages=[
113+
{
114+
"role": "user",
115+
"content": [
116+
{"type": "text", "text": "What's in this image?"},
117+
{
118+
"type": "image_url",
119+
"image_url": {"url": f"data:image/jpeg;base64,{image_url}"},
120+
"detail": "auto",
121+
},
122+
],
123+
}
124+
],
125+
max_tokens=140,
126+
)
127+
description = response.choices[0].message[1].content[0].text
128+
print(f"get_image_description: {description}")
129+
130+
return response.choices[0].message[1].content[0].text
131+
132+
133+
def create_metadata():
134+
metadata_list = []
135+
counter = 0
136+
total_items = len([filename for filename in os.listdir(watermarks_dir_path)])
137+
138+
for filename in os.listdir(watermarks_dir_path):
139+
if thumbnail_extension not in filename and (
140+
filename.lower().endswith(".png") or filename.lower().endswith(".jpg")
141+
):
142+
# Create a variable for the actual file
143+
file_path = os.path.join(watermarks_dir_path, filename)
144+
# base64_image = encode_image(file_path)
145+
146+
# Upload the file to IPFS and get the IPFS hash
147+
image_ipfs_hash = upload_file_to_ipfs(file_path)
148+
print(f"create_metadata.image_ipfs_hash: {image_ipfs_hash}")
149+
150+
# change the file name to include _thumbnail
151+
file_extension = filename.split(".")[-1]
152+
name = filename.split(".")[0]
153+
thumbnail_filename = name + thumbnail_extension + "." + file_extension
154+
thumbnail_path = os.path.join(watermarks_dir_path, thumbnail_filename)
155+
thumbnail_ipfs_hash = upload_file_to_ipfs(thumbnail_path)
156+
print(f"create_metadata.thumbnail_ipfs_hash: {thumbnail_ipfs_hash}")
157+
158+
# description = get_image_description(f"{ipfs_gateway_url}{image_ipfs_hash}")
159+
160+
# Create a metadata object
161+
metadata = {
162+
"name": name,
163+
"description": "Experience the captivating world of dark art through the mesmerizing creations of Lars Kristo. Delve into the depths of the human psyche as each piece unveils a haunting narrative, blending beauty and darkness in a unique and thought-provoking way. With intricate details and a mastery of technique, this artist pushes the boundaries of conventional art, inviting you to explore the shadows and embrace the enigmatic allure of the unknown.",
164+
"image": f"{ipfs_gateway_url}{image_ipfs_hash}",
165+
"thumbnail": f"{ipfs_gateway_url}{thumbnail_ipfs_hash}",
166+
}
167+
168+
# Append the metadata object to the list
169+
metadata_list.append(metadata)
170+
counter += 1
171+
print(f"create_metadata: {counter} of {total_items} items")
172+
173+
# Write the list of metadata objects to a JSON file
174+
with open("metadata.json", "w") as f:
175+
json.dump(metadata_list, f)
176+
177+
178+
def main():
179+
create_metadata()
180+
# create_img_thumbnails()
181+
# add_image_watermark()
182+
183+
184+
if __name__ == "__main__":
185+
main()

0 commit comments

Comments
 (0)