Update app.py
Browse files
app.py
CHANGED
|
@@ -4,22 +4,22 @@ from tensorflow import keras
|
|
| 4 |
from tensorflow.keras import layers
|
| 5 |
import numpy as np
|
| 6 |
import os
|
| 7 |
-
from PIL import Image
|
| 8 |
|
| 9 |
# =========================================
|
| 10 |
-
# 1. SETTINGS
|
| 11 |
# =========================================
|
| 12 |
-
IMG_SIZE = 48
|
| 13 |
CHANNELS = 3
|
| 14 |
-
TIMESTEPS =
|
| 15 |
BATCH_SIZE = 32
|
| 16 |
-
WEIGHTS_FILE = "
|
| 17 |
|
| 18 |
# =========================================
|
| 19 |
-
# 2.
|
| 20 |
# =========================================
|
| 21 |
-
def generate_veda_patterns(num_images=
|
| 22 |
-
print(f"Generating {num_images}
|
| 23 |
data = []
|
| 24 |
|
| 25 |
for _ in range(num_images):
|
|
@@ -27,24 +27,34 @@ def generate_veda_patterns(num_images=500):
|
|
| 27 |
y = np.linspace(-1, 1, IMG_SIZE)
|
| 28 |
X, Y = np.meshgrid(x, y)
|
| 29 |
|
| 30 |
-
|
|
|
|
| 31 |
phase = np.random.uniform(0, np.pi)
|
| 32 |
-
center_x = np.random.uniform(-0.5, 0.5)
|
| 33 |
-
center_y = np.random.uniform(-0.5, 0.5)
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
|
| 38 |
-
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
g_boost = np.random.rand()
|
| 42 |
-
b_boost = np.random.rand()
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
img[:, :, 2] = (pattern + 1) / 2 * b_boost
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
data.append(img)
|
| 49 |
|
| 50 |
return np.array(data).astype("float32")
|
|
@@ -65,55 +75,54 @@ def forward_noise(x_0, t):
|
|
| 65 |
return (tf.sqrt(a_bar) * x_0) + (tf.sqrt(1.0 - a_bar) * noise), noise
|
| 66 |
|
| 67 |
# =========================================
|
| 68 |
-
# 4.
|
| 69 |
# =========================================
|
| 70 |
def build_unet():
|
| 71 |
image_input = layers.Input(shape=(IMG_SIZE, IMG_SIZE, CHANNELS))
|
| 72 |
time_input = layers.Input(shape=(1,))
|
| 73 |
|
| 74 |
-
#
|
| 75 |
-
t = layers.Dense(32, activation="
|
| 76 |
t = layers.Reshape((1, 1, 32))(t)
|
| 77 |
|
| 78 |
-
# In
|
| 79 |
-
x = layers.Conv2D(32, 3, padding="same", activation="
|
| 80 |
-
|
| 81 |
-
# MERGE: Now both x (..., 32) and t (..., 32) match!
|
| 82 |
x = layers.Add()([x, t])
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 89 |
-
x = layers.Conv2DTranspose(
|
| 90 |
-
x = layers.
|
|
|
|
| 91 |
|
| 92 |
outputs = layers.Conv2D(CHANNELS, 1, padding="same")(x)
|
| 93 |
return keras.Model([image_input, time_input], outputs)
|
| 94 |
|
| 95 |
-
# Initialize
|
| 96 |
model = build_unet()
|
| 97 |
optimizer = keras.optimizers.Adam(learning_rate=1e-4)
|
| 98 |
loss_fn = keras.losses.MeanSquaredError()
|
| 99 |
|
| 100 |
-
# Load weights if available
|
| 101 |
if os.path.exists(WEIGHTS_FILE):
|
| 102 |
try:
|
| 103 |
model.load_weights(WEIGHTS_FILE)
|
| 104 |
-
print("Brain Loaded!")
|
| 105 |
-
except
|
| 106 |
-
print(f"Starting fresh brain: {e}")
|
| 107 |
|
| 108 |
# =========================================
|
| 109 |
-
# 5. TRAINING
|
| 110 |
# =========================================
|
| 111 |
def train_model(epochs):
|
| 112 |
-
yield "Generating
|
| 113 |
-
x_train = generate_veda_patterns(num_images=
|
| 114 |
-
dataset = tf.data.Dataset.from_tensor_slices(x_train).batch(BATCH_SIZE).shuffle(
|
| 115 |
|
| 116 |
-
yield "Dataset Ready.
|
| 117 |
|
| 118 |
for epoch in range(int(epochs)):
|
| 119 |
total_loss = 0
|
|
@@ -133,18 +142,16 @@ def train_model(epochs):
|
|
| 133 |
steps += 1
|
| 134 |
|
| 135 |
model.save_weights(WEIGHTS_FILE)
|
| 136 |
-
yield f"Epoch {epoch+1}/{epochs}
|
| 137 |
|
| 138 |
-
yield "Training
|
| 139 |
|
| 140 |
# =========================================
|
| 141 |
-
# 6. GENERATION
|
| 142 |
# =========================================
|
| 143 |
def generate_art():
|
| 144 |
-
# Start with static
|
| 145 |
img = tf.random.normal((1, IMG_SIZE, IMG_SIZE, CHANNELS), dtype=tf.float32)
|
| 146 |
|
| 147 |
-
# Reverse Diffusion
|
| 148 |
for i in range(TIMESTEPS - 1, 0, -1):
|
| 149 |
t = tf.fill([1], i)
|
| 150 |
pred_noise = model([img, t], training=False)
|
|
@@ -162,35 +169,36 @@ def generate_art():
|
|
| 162 |
z = tf.random.normal((1, IMG_SIZE, IMG_SIZE, CHANNELS), dtype=tf.float32)
|
| 163 |
img = img + (tf.sqrt(beta_t) * z)
|
| 164 |
|
| 165 |
-
#
|
| 166 |
img = tf.clip_by_value(img, 0.0, 1.0)
|
| 167 |
img = img[0].numpy()
|
| 168 |
img = (img * 255).astype(np.uint8)
|
| 169 |
|
| 170 |
-
#
|
|
|
|
| 171 |
pil_img = Image.fromarray(img)
|
| 172 |
-
pil_img = pil_img.resize((
|
|
|
|
| 173 |
return pil_img
|
| 174 |
|
| 175 |
# =========================================
|
| 176 |
# 7. UI
|
| 177 |
# =========================================
|
| 178 |
def run_training_wrapper():
|
| 179 |
-
for update in train_model(
|
| 180 |
yield update
|
| 181 |
|
| 182 |
with gr.Blocks(title="Akasha Art Engine") as demo:
|
| 183 |
-
gr.Markdown("# Akasha Art Engine")
|
| 184 |
-
gr.Markdown("
|
| 185 |
|
| 186 |
with gr.Tab("Dream"):
|
| 187 |
-
gen_btn = gr.Button("Generate
|
| 188 |
out_img = gr.Image(label="Veda Dream")
|
| 189 |
gen_btn.click(generate_art, outputs=out_img)
|
| 190 |
|
| 191 |
with gr.Tab("Train"):
|
| 192 |
-
gr.
|
| 193 |
-
train_btn = gr.Button("Train AI (5 Epochs)")
|
| 194 |
log = gr.Textbox(label="Status")
|
| 195 |
train_btn.click(run_training_wrapper, outputs=log)
|
| 196 |
|
|
|
|
| 4 |
from tensorflow.keras import layers
|
| 5 |
import numpy as np
|
| 6 |
import os
|
| 7 |
+
from PIL import Image, ImageFilter
|
| 8 |
|
| 9 |
# =========================================
|
| 10 |
+
# 1. HIGH QUALITY SETTINGS
|
| 11 |
# =========================================
|
| 12 |
+
IMG_SIZE = 64 # Increased from 48 to 64 (Better detail)
|
| 13 |
CHANNELS = 3
|
| 14 |
+
TIMESTEPS = 300 # More steps = smoother transitions
|
| 15 |
BATCH_SIZE = 32
|
| 16 |
+
WEIGHTS_FILE = "veda_hq_model.weights.h5"
|
| 17 |
|
| 18 |
# =========================================
|
| 19 |
+
# 2. SHARP VEDA PATTERNS (Improved Math)
|
| 20 |
# =========================================
|
| 21 |
+
def generate_veda_patterns(num_images=600):
|
| 22 |
+
print(f"Generating {num_images} Sharp Veda patterns...")
|
| 23 |
data = []
|
| 24 |
|
| 25 |
for _ in range(num_images):
|
|
|
|
| 27 |
y = np.linspace(-1, 1, IMG_SIZE)
|
| 28 |
X, Y = np.meshgrid(x, y)
|
| 29 |
|
| 30 |
+
# Parameters
|
| 31 |
+
freq = np.random.uniform(3, 12)
|
| 32 |
phase = np.random.uniform(0, np.pi)
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# Radial Geometry
|
| 35 |
+
R = np.sqrt(X**2 + Y**2)
|
| 36 |
|
| 37 |
+
# Sharper Math: We combine Sine with Tanh to create harder edges
|
| 38 |
+
pattern = np.tanh(np.sin(freq * R - phase) * 5)
|
| 39 |
|
| 40 |
+
img = np.zeros((IMG_SIZE, IMG_SIZE, 3))
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
# Cosmic Colors (Deep Purples, Golds, Blues)
|
| 43 |
+
color_scheme = np.random.randint(0, 3)
|
|
|
|
| 44 |
|
| 45 |
+
if color_scheme == 0: # Fire
|
| 46 |
+
img[:, :, 0] = (pattern + 1) / 2 * 1.0 # R
|
| 47 |
+
img[:, :, 1] = (pattern + 1) / 2 * 0.5 # G
|
| 48 |
+
img[:, :, 2] = (pattern + 1) / 2 * 0.1 # B
|
| 49 |
+
elif color_scheme == 1: # Water/Space
|
| 50 |
+
img[:, :, 0] = (pattern + 1) / 2 * 0.1
|
| 51 |
+
img[:, :, 1] = (pattern + 1) / 2 * 0.4
|
| 52 |
+
img[:, :, 2] = (pattern + 1) / 2 * 1.0
|
| 53 |
+
else: # Spirit
|
| 54 |
+
img[:, :, 0] = (pattern + 1) / 2 * 0.8
|
| 55 |
+
img[:, :, 1] = (pattern + 1) / 2 * 0.2
|
| 56 |
+
img[:, :, 2] = (pattern + 1) / 2 * 0.8
|
| 57 |
+
|
| 58 |
data.append(img)
|
| 59 |
|
| 60 |
return np.array(data).astype("float32")
|
|
|
|
| 75 |
return (tf.sqrt(a_bar) * x_0) + (tf.sqrt(1.0 - a_bar) * noise), noise
|
| 76 |
|
| 77 |
# =========================================
|
| 78 |
+
# 4. DEEPER U-NET (BRAIN)
|
| 79 |
# =========================================
|
| 80 |
def build_unet():
|
| 81 |
image_input = layers.Input(shape=(IMG_SIZE, IMG_SIZE, CHANNELS))
|
| 82 |
time_input = layers.Input(shape=(1,))
|
| 83 |
|
| 84 |
+
# Map time to 32 dimensions matches the first Conv layer
|
| 85 |
+
t = layers.Dense(32, activation="swish")(time_input) # Swish is better than Relu
|
| 86 |
t = layers.Reshape((1, 1, 32))(t)
|
| 87 |
|
| 88 |
+
# In
|
| 89 |
+
x = layers.Conv2D(32, 3, padding="same", activation="swish")(image_input)
|
|
|
|
|
|
|
| 90 |
x = layers.Add()([x, t])
|
| 91 |
|
| 92 |
+
# Downsample
|
| 93 |
+
x1 = layers.Conv2D(64, 3, strides=2, padding="same", activation="swish")(x) # 32x32
|
| 94 |
+
x2 = layers.Conv2D(128, 3, strides=2, padding="same", activation="swish")(x1) # 16x16
|
| 95 |
+
|
| 96 |
+
# Bottleneck
|
| 97 |
+
x3 = layers.Conv2D(256, 3, padding="same", activation="swish")(x2)
|
| 98 |
|
| 99 |
+
# Upsample
|
| 100 |
+
x = layers.Conv2DTranspose(128, 3, strides=2, padding="same", activation="swish")(x3)
|
| 101 |
+
x = layers.Conv2DTranspose(64, 3, strides=2, padding="same", activation="swish")(x)
|
| 102 |
+
x = layers.Conv2D(32, 3, padding="same", activation="swish")(x)
|
| 103 |
|
| 104 |
outputs = layers.Conv2D(CHANNELS, 1, padding="same")(x)
|
| 105 |
return keras.Model([image_input, time_input], outputs)
|
| 106 |
|
|
|
|
| 107 |
model = build_unet()
|
| 108 |
optimizer = keras.optimizers.Adam(learning_rate=1e-4)
|
| 109 |
loss_fn = keras.losses.MeanSquaredError()
|
| 110 |
|
|
|
|
| 111 |
if os.path.exists(WEIGHTS_FILE):
|
| 112 |
try:
|
| 113 |
model.load_weights(WEIGHTS_FILE)
|
| 114 |
+
print("HQ Brain Loaded!")
|
| 115 |
+
except: pass
|
|
|
|
| 116 |
|
| 117 |
# =========================================
|
| 118 |
+
# 5. TRAINING
|
| 119 |
# =========================================
|
| 120 |
def train_model(epochs):
|
| 121 |
+
yield "Generating HD Data (Math)..."
|
| 122 |
+
x_train = generate_veda_patterns(num_images=600)
|
| 123 |
+
dataset = tf.data.Dataset.from_tensor_slices(x_train).batch(BATCH_SIZE).shuffle(600)
|
| 124 |
|
| 125 |
+
yield "Dataset Ready. Training..."
|
| 126 |
|
| 127 |
for epoch in range(int(epochs)):
|
| 128 |
total_loss = 0
|
|
|
|
| 142 |
steps += 1
|
| 143 |
|
| 144 |
model.save_weights(WEIGHTS_FILE)
|
| 145 |
+
yield f"Epoch {epoch+1}/{epochs} - Loss: {total_loss/steps:.4f}"
|
| 146 |
|
| 147 |
+
yield "Training Complete."
|
| 148 |
|
| 149 |
# =========================================
|
| 150 |
+
# 6. GENERATION (WITH UPSCALING)
|
| 151 |
# =========================================
|
| 152 |
def generate_art():
|
|
|
|
| 153 |
img = tf.random.normal((1, IMG_SIZE, IMG_SIZE, CHANNELS), dtype=tf.float32)
|
| 154 |
|
|
|
|
| 155 |
for i in range(TIMESTEPS - 1, 0, -1):
|
| 156 |
t = tf.fill([1], i)
|
| 157 |
pred_noise = model([img, t], training=False)
|
|
|
|
| 169 |
z = tf.random.normal((1, IMG_SIZE, IMG_SIZE, CHANNELS), dtype=tf.float32)
|
| 170 |
img = img + (tf.sqrt(beta_t) * z)
|
| 171 |
|
| 172 |
+
# Process
|
| 173 |
img = tf.clip_by_value(img, 0.0, 1.0)
|
| 174 |
img = img[0].numpy()
|
| 175 |
img = (img * 255).astype(np.uint8)
|
| 176 |
|
| 177 |
+
# HIGH QUALITY RESIZE (LANCZOS)
|
| 178 |
+
# This blurs the pixels so it looks like smooth art, not blocks
|
| 179 |
pil_img = Image.fromarray(img)
|
| 180 |
+
pil_img = pil_img.resize((512, 512), Image.LANCZOS)
|
| 181 |
+
|
| 182 |
return pil_img
|
| 183 |
|
| 184 |
# =========================================
|
| 185 |
# 7. UI
|
| 186 |
# =========================================
|
| 187 |
def run_training_wrapper():
|
| 188 |
+
for update in train_model(10): # Default 10 Epochs for better quality
|
| 189 |
yield update
|
| 190 |
|
| 191 |
with gr.Blocks(title="Akasha Art Engine") as demo:
|
| 192 |
+
gr.Markdown("# Akasha Art Engine (High Quality)")
|
| 193 |
+
gr.Markdown("Generating 64x64 math patterns and upscaling to 512x512.")
|
| 194 |
|
| 195 |
with gr.Tab("Dream"):
|
| 196 |
+
gen_btn = gr.Button("Generate Energy Pattern", variant="primary")
|
| 197 |
out_img = gr.Image(label="Veda Dream")
|
| 198 |
gen_btn.click(generate_art, outputs=out_img)
|
| 199 |
|
| 200 |
with gr.Tab("Train"):
|
| 201 |
+
train_btn = gr.Button("Train AI (10 Epochs - Takes ~5 mins)")
|
|
|
|
| 202 |
log = gr.Textbox(label="Status")
|
| 203 |
train_btn.click(run_training_wrapper, outputs=log)
|
| 204 |
|