-
Notifications
You must be signed in to change notification settings - Fork 6
/
gas.py
195 lines (159 loc) · 8.31 KB
/
gas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import numpy as np
import os
import sys
import uuid
import datetime
import hashlib
import time
import shutil
import PIL
from tensorflow.keras.models import load_model
from PIL import Image
import matplotlib.pyplot as plt
from subprocess import call
from methods import *
NUM_SAMPLES = 1000
rate_model = load_model('rate_model.h5');
rate_size = 224
project_files = ['gas.py', 'methods.py']
#create run's folder
generation_date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
folder_name = ('Run %s' % generation_date.replace(':', '-')).replace(' ', '_') #
os.mkdir(folder_name)
#save copy of project files into run's backup folder (useful if you ever want to modify the project)
backup_folder = os.path.join(folder_name,'backup')
os.mkdir(backup_folder)
for file in project_files:
shutil.copyfile(file, os.path.join(backup_folder,file))
#finds the date of last modified file, so we know when the project was modified last time
#finds hash of all main files of the project, to know to which iteration of it the generated program belongs to
gas_date = 0
binary_gas_hash = bytes.fromhex('00000000000000000000000000000000')
for file_path in project_files:
file_date = os.path.getmtime(file_path)
if file_date > gas_date: gas_date = file_date
with open(file_path, "r") as file:
data = file.read().encode('utf-8')
file_hash = hashlib.md5(data).hexdigest()
binary_file_hash = bytes.fromhex(file_hash)
binary_gas_hash = bytes(x ^ y for x, y in zip(binary_gas_hash, binary_file_hash))
gas_hash = binary_gas_hash.hex()
gas_date = datetime.datetime.utcfromtimestamp(gas_date).strftime("%Y-%m-%d %H:%M:%S UTC")
print ('Current GAS hash:', gas_hash)
print ('Current GAS date:', gas_date)
methods = {k: v for k, v in methods.items() if v['active']}
methods_names = list(methods.keys())
#set probabilities for different methods, if they are not defined already
methods_prob = np.abs(np.random.normal(0, 1, size = len(methods)))
for ind in range(len(methods_names)):
method = methods[methods_names[ind]]
if 'weight' in method:
methods_prob[ind] = method['weight']
methods_prob = methods_prob / np.sum(methods_prob)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.barh(methods_names, methods_prob)
plt.savefig(os.path.join(backup_folder,'probs.png'), bbox_inches='tight')
scores = []
for i in range(NUM_SAMPLES):
file_uuid = str(uuid.uuid4())
script_name = os.path.join(folder_name, file_uuid + ".py")
with open(script_name, "w") as file:
step_1 = """# This program was generated by "Generative Art Synthesizer" \n"""
step_1 += """# Generation date: %s \n""" % (generation_date)
step_1 += """# GAS change date: %s \n""" % (gas_date)
step_1 += """# GAS md5 hash: %s \n""" % (gas_hash)
step_1 += """# Python version: %s \n""" % "".join(list(s for s in sys.version if s. isprintable()))
step_1 += """# For more information visit: https://github.com/volotat/GAS \n"""
step_1 += """\n"""
step_1 += """#import python libraries \n"""
step_1 += """import os #%s \n""" % ('OS version: default' )
step_1 += """import numpy as np #%s \n""" % ('Numpy version: ' + np.__version__)
step_1 += """from PIL import Image #%s \n""" % ('PIL version: ' + PIL.__version__)
step_1 += """\n"""
file.write(step_1)
step_2 = """#set initial params \n"""
step_2 += """SIZE = 384 \n"""
step_2 += """GRID_CHANNELS = %d \n""" % (GRID_CHANNELS)
step_2 += """\n"""
file.write(step_2)
step_3 = """#define utility methods \n"""
step_3 += """def test_values(arr): \n"""
step_3 += """ if np.isnan(arr).any(): \n"""
step_3 += """ raise Exception('Array has None elements!') \n"""
step_3 += """ \n"""
step_3 += """ if np.amin(arr) < -1 or np.amax(arr) > 1: \n"""
step_3 += """ raise Exception('Values went to far! [ %.2f : %.2f ]'%(np.amin(arr), np.amax(arr)) ) \n"""
step_3 += """ \n"""
step_3 += """ return arr \n"""
step_3 += """\n"""
step_3 += """#define grid transformation methods"""
for method in methods:
step_3 += methods[method]['define']
step_3 += """\n"""
step_3 += """\n"""
file.write(step_3)
step_4 = """#set initial grid \n"""
step_4 += """grid = np.zeros((SIZE, SIZE, GRID_CHANNELS)) \n"""
step_4 += """\n"""
step_4 += """x = ((np.arange(SIZE)/(SIZE-1) - 0.5) * 2).reshape((1, SIZE)).repeat(SIZE, 0) \n"""
step_4 += """y = ((np.arange(SIZE)/(SIZE-1) - 0.5) * 2).reshape((SIZE, 1)).repeat(SIZE, 1) \n"""
step_4 += """\n"""
for j in range(GRID_CHANNELS):
ma, mb = np.random.uniform(-1, 1, 2)
step_4 += """grid[:,:,%s] = (x * %s + y * %s) / 2 \n""" % (repr(j), repr(ma), repr(mb))
step_4 += """\n"""
file.write(step_4)
step_5 = """#apply transformations to the grid \n"""
steps = np.random.randint(MIN_DEEP, MAX_DEEP)
for j in range(steps):
method_ind = np.random.choice(len(methods_names), None, replace=False, p = methods_prob)
method_name = methods_names[method_ind]
step_5 += methods[method_name]['transform']()
step_5 += """\n"""
file.write(step_5)
step_6 = """#create color space \n"""
step_6 += """def shift_colors(x, shift): \n"""
step_6 += """ res = x.copy() \n"""
step_6 += """ for i in range(x.shape[-1]): \n"""
step_6 += """ shift[i] = -shift[i] \n"""
step_6 += """ if shift[i] > 0: res[:,:,i] = (-np.abs(((x[:,:,i] + 1) / 2) ** (1 + shift[i]) - 1) ** (1 / (1 + shift[i])) + 1) * 2 - 1 \n"""
step_6 += """ if shift[i] < 0: res[:,:,i] = np.abs((1 - (x [:,:,i]+ 1) / 2) ** (1 - shift[i]) - 1) ** (1 / (1 - shift[i])) * 2 - 1 \n"""
step_6 += """ return test_values(res) \n"""
step_6 += """\n"""
step_6 += """res = np.zeros((SIZE, SIZE, 3)) \n"""
count = random_normal_int(GRID_CHANNELS) + 1
for k in range(count):
step_6 += """res += shift_colors(grid[:,:,%s:%s].repeat(3, -1), %s) \n""" % (repr(k), repr(k+1), repr(list(np.abs(np.random.normal(0, 3, 3)))))
step_6 += """\n"""
step_6 += """res = res / %s \n""" % count
step_6 += """res = ((res + 1) / 2) ** 2.5 \n"""
step_6 += """res = (res * 255).clip(0,255) \n"""
step_6 += """\n"""
file.write(step_6)
step_7 = """#save results \n"""
step_7 += """im = Image.fromarray(np.uint8(res)) \n"""
step_7 += """im.save(os.path.basename(__file__) + '.png') \n"""
step_7 += """\n"""
step_7 += """#save layers \n"""
step_7 += """img = np.zeros((SIZE * 4, SIZE * 4)) \n"""
step_7 += """for j in range(GRID_CHANNELS): \n"""
step_7 += """ x = j % 4 \n"""
step_7 += """ y = j // 4 \n"""
step_7 += """ img[x*SIZE:(x + 1)*SIZE, y*SIZE:(y+1)*SIZE] = grid[:,:,j] \n"""
step_7 += """\n"""
step_7 += """img = (img + 1) * 127.5 \n"""
step_7 += """im = Image.fromarray(np.uint8(img)) \n"""
step_7 += """im.save(os.path.basename(__file__) + '_layers.png') \n"""
file.write(step_7)
call(["python", file_uuid + ".py"], cwd=folder_name)
img = Image.open(os.path.join(folder_name, file_uuid + ".py.png")).convert('RGB').resize((rate_size, rate_size), Image.BILINEAR);
data = np.array(img) / 127.5 - 1
score = rate_model.predict(data.reshape((1, rate_size, rate_size, 3)))[0]
os.rename(os.path.join(folder_name, "%s.py"%file_uuid), os.path.join(folder_name, "[%.2f] %s.py"%(score, file_uuid)))
os.rename(os.path.join(folder_name, "%s.py.png"%file_uuid), os.path.join(folder_name, "[%.2f] %s.py.png"%(score, file_uuid)))
os.rename(os.path.join(folder_name, "%s.py_layers.png"%file_uuid), os.path.join(folder_name, "[%.2f] %s.py_layers.png"%(score, file_uuid)))
print("%d : %s [%.2f]" % (i + 1, file_uuid, score))
scores.append(score)
print("Average score : %.2f" % np.mean(scores))
print("Max score : %.2f" % np.amax(scores))