vedaco commited on
Commit
a92b797
·
verified ·
1 Parent(s): 6e860f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -57
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 = 200
15
  BATCH_SIZE = 32
16
- WEIGHTS_FILE = "veda_art_model.weights.h5"
17
 
18
  # =========================================
19
- # 2. GENERATE CUSTOM "VEDA" DATASET (MATH ART)
20
  # =========================================
21
- def generate_veda_patterns(num_images=500):
22
- print(f"Generating {num_images} unique Veda patterns...")
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
- freq = np.random.uniform(2, 10)
 
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
- R = np.sqrt((X - center_x)**2 + (Y - center_y)**2)
36
- pattern = np.sin(freq * R - phase)
37
 
38
- img = np.zeros((IMG_SIZE, IMG_SIZE, 3))
 
39
 
40
- r_boost = np.random.rand()
41
- g_boost = np.random.rand()
42
- b_boost = np.random.rand()
43
 
44
- img[:, :, 0] = (pattern + 1) / 2 * r_boost
45
- img[:, :, 1] = (pattern + 1) / 2 * g_boost
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. THE BRAIN (U-NET) - FIXED SHAPES
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
- # FIX: We map time to 32 dimensions (not IMG_SIZE) to match the Conv2D layer
75
- t = layers.Dense(32, activation="relu")(time_input)
76
  t = layers.Reshape((1, 1, 32))(t)
77
 
78
- # In: This Conv2D produces 32 filters
79
- x = layers.Conv2D(32, 3, padding="same", activation="relu")(image_input)
80
-
81
- # MERGE: Now both x (..., 32) and t (..., 32) match!
82
  x = layers.Add()([x, t])
83
 
84
- x = layers.Conv2D(64, 3, strides=2, padding="same", activation="relu")(x)
85
- x = layers.Conv2D(128, 3, strides=2, padding="same", activation="relu")(x)
86
- x = layers.Conv2D(256, 3, padding="same", activation="relu")(x)
 
 
 
87
 
88
- x = layers.Conv2DTranspose(128, 3, strides=2, padding="same", activation="relu")(x)
89
- x = layers.Conv2DTranspose(64, 3, strides=2, padding="same", activation="relu")(x)
90
- x = layers.Conv2D(32, 3, padding="same", activation="relu")(x)
 
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 Exception as e:
106
- print(f"Starting fresh brain: {e}")
107
 
108
  # =========================================
109
- # 5. TRAINING FUNCTION
110
  # =========================================
111
  def train_model(epochs):
112
- yield "Generating Sacred Geometry Data..."
113
- x_train = generate_veda_patterns(num_images=500)
114
- dataset = tf.data.Dataset.from_tensor_slices(x_train).batch(BATCH_SIZE).shuffle(500)
115
 
116
- yield "Dataset Ready. Starting Training Loop..."
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} Complete - Loss: {total_loss/steps:.4f}"
137
 
138
- yield "Training Done! Go to 'Dream' tab."
139
 
140
  # =========================================
141
- # 6. GENERATION FUNCTION
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
- # Normalize
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
- # Resize
 
171
  pil_img = Image.fromarray(img)
172
- pil_img = pil_img.resize((300, 300), Image.BILINEAR)
 
173
  return pil_img
174
 
175
  # =========================================
176
  # 7. UI
177
  # =========================================
178
  def run_training_wrapper():
179
- for update in train_model(5):
180
  yield update
181
 
182
  with gr.Blocks(title="Akasha Art Engine") as demo:
183
- gr.Markdown("# Akasha Art Engine")
184
- gr.Markdown("A custom Diffusion model that learns sacred geometry from pure math.")
185
 
186
  with gr.Tab("Dream"):
187
- gen_btn = gr.Button("Generate Sacred Pattern", variant="primary")
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.Markdown("Click below to generate data and train the model.")
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