-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1507 lines (1226 loc) · 68.5 KB
/
app.py
File metadata and controls
1507 lines (1226 loc) · 68.5 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import numpy as np
from PIL import Image
import io
import matplotlib.pyplot as pltF
import gc
import os
# Add these imports at the top of your file
from tinydb import TinyDB, Query
import base64
import datetime
import matplotlib.pyplot as plt
# Set page config with colorful theme
st.set_page_config(
page_title="AI Art Generator - GAN Training Studio",
layout="wide",
initial_sidebar_state="expanded",
page_icon="🎨"
)
# --- Background Image Encoding ---
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
def set_png_as_page_bg(bin_file):
bin_str = get_base64_of_bin_file(bin_file)
page_bg_img = f'''
<style>
.stApp {{
background-image: url("data:image/png;base64,{bin_str}");
background-size: cover;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
image-rendering: pixelated;
}}
</style>
'''
st.markdown(page_bg_img, unsafe_allow_html=True)
# Set the local background image
if os.path.exists("image.png"):
set_png_as_page_bg("image.png")
# Custom CSS for magical, dreamy, transparent pixel image
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');
/* Make the main containers and header totally transparent */
[data-testid="stAppViewContainer"],
[data-testid="stHeader"] {
background-color: transparent !important;
}
/* Full Transparency sidebar */
[data-testid="stSidebar"] {
background-color: transparent !important;
border-right: 1px solid rgba(255, 255, 255, 0.1);
}
/* Sidebar inner content background reset */
[data-testid="stSidebar"] > div:first-child {
background-color: transparent !important;
}
/* Main block container - Full Transparency */
.block-container {
background-color: transparent !important;
border-radius: 20px;
padding: 2.5rem 3.5rem !important;
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: none !important;
}
/* Removed all text shadows entirely to avoid any dark/grey shading as requested */
p, span, label, div, li, h2, h3, h4, h5, h6 {
text-shadow: none !important;
}
.big-title {
font-family: 'Press Start 2P', cursive !important;
font-size: 2.5rem !important;
/* Exact color match from pixel bg: Pink, Blue, Gold trail */
background: linear-gradient(to right, #ff44cc, #44ccff, #ffcc33);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
margin-bottom: 2rem !important;
text-shadow: none !important;
filter: none !important;
}
/* Clean subtle subtitle */
.main-subtitle h3 {
color: #f0f0f0 !important;
text-shadow: none !important;
font-weight: 300 !important;
}
/* Fully Transparent inputs */
div[data-baseweb="select"] > div,
input,
div[data-testid="stFileUploader"] {
background-color: rgba(0, 0, 0, 0.2) !important; /* Extremely light touch */
border: 1px solid rgba(255, 255, 255, 0.2) !important;
border-radius: 8px;
}
/* Tab transparency */
button[data-baseweb="tab"] {
background-color: transparent !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
border-radius: 10px 10px 0 0;
margin-right: 5px;
}
button[data-baseweb="tab"][aria-selected="true"] {
background-color: rgba(255,255,255,0.15) !important;
border-bottom: 2px solid #4ecdc4 !important;
}
/* Make specific nested blocks more transparent to not stack too darkly */
[data-testid="stVerticalBlock"] {
background-color: transparent !important;
}
</style>
""", unsafe_allow_html=True)
# Device configuration for memory efficiency
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class Generator128(nn.Module):
"""Generator capable of producing 128x128 images."""
def __init__(self, latent_dim=100, img_channels=3, feature_maps=64):
super().__init__()
self.main = nn.Sequential(
# Input: Z (latent vector)
nn.ConvTranspose2d(latent_dim, feature_maps * 16, 4, 1, 0, bias=False),
nn.BatchNorm2d(feature_maps * 16),
nn.ReLU(True),
# State size: (feature_maps*16) x 4 x 4
nn.ConvTranspose2d(feature_maps * 16, feature_maps * 8, 4, 2, 1, bias=False),
nn.BatchNorm2d(feature_maps * 8),
nn.ReLU(True),
# State size: (feature_maps*8) x 8 x 8
nn.ConvTranspose2d(feature_maps * 8, feature_maps * 4, 4, 2, 1, bias=False),
nn.BatchNorm2d(feature_maps * 4),
nn.ReLU(True),
# State size: (feature_maps*4) x 16 x 16
nn.ConvTranspose2d(feature_maps * 4, feature_maps * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(feature_maps * 2),
nn.ReLU(True),
# State size: (feature_maps*2) x 32 x 32
nn.ConvTranspose2d(feature_maps * 2, feature_maps, 4, 2, 1, bias=False),
nn.BatchNorm2d(feature_maps),
nn.ReLU(True),
# State size: (feature_maps) x 64 x 64
# --- NEW LAYER FOR 128x128 ---
nn.ConvTranspose2d(feature_maps, img_channels, 4, 2, 1, bias=False),
nn.Tanh()
# Final state size: (img_channels) x 128 x 128
)
def forward(self, z):
z = z.view(z.shape[0], -1, 1, 1)
return self.main(z)
class Discriminator128(nn.Module):
"""Discriminator capable of handling 128x128 images."""
def __init__(self, img_channels=3, feature_maps=64):
super().__init__()
self.main = nn.Sequential(
# --- NEW LAYER FOR 128x128 INPUT ---
# Input size: (img_channels) x 128 x 128
nn.Conv2d(img_channels, feature_maps, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps) x 64 x 64
nn.Conv2d(feature_maps, feature_maps * 2, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 2, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*2) x 32 x 32
nn.Conv2d(feature_maps * 2, feature_maps * 4, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 4, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*4) x 16 x 16
nn.Conv2d(feature_maps * 4, feature_maps * 8, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 8, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*8) x 8 x 8
nn.Conv2d(feature_maps * 8, feature_maps * 16, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 16, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*16) x 4 x 4
nn.Conv2d(feature_maps * 16, 1, 4, 1, 0, bias=False),
)
def forward(self, img):
return self.main(img)
# ===================== SIMPLE GAN MODELS =====================
class SimpleGenerator(nn.Module):
"""Lightweight generator network"""
def __init__(self, latent_dim=100, img_channels=3, img_size=64):
super().__init__()
self.img_size = img_size
self.img_channels = img_channels
# Calculate initial size for reshape
init_size = img_size // 4
self.init_size = init_size
self.linear = nn.Sequential(
nn.Linear(latent_dim, 128 * init_size ** 2),
nn.LeakyReLU(0.2)
)
self.conv_blocks = nn.Sequential(
nn.BatchNorm2d(128),
nn.Upsample(scale_factor=2),
nn.Conv2d(128, 128, 3, stride=1, padding=1),
nn.BatchNorm2d(128),
nn.LeakyReLU(0.2),
nn.Upsample(scale_factor=2),
nn.Conv2d(128, 64, 3, stride=1, padding=1),
nn.BatchNorm2d(64),
nn.LeakyReLU(0.2),
nn.Conv2d(64, img_channels, 3, stride=1, padding=1),
nn.Tanh()
)
def forward(self, z):
out = self.linear(z)
out = out.view(out.shape[0], 128, self.init_size, self.init_size)
img = self.conv_blocks(out)
return img
class SimpleDiscriminator(nn.Module):
"""Lightweight discriminator network"""
def __init__(self, img_channels=3, img_size=64):
super().__init__()
def discriminator_block(in_filters, out_filters, stride=2):
return [
nn.Conv2d(in_filters, out_filters, 3, stride, 1),
nn.LeakyReLU(0.2),
nn.Dropout2d(0.25)
]
self.model = nn.Sequential(
*discriminator_block(img_channels, 16, 2),
*discriminator_block(16, 32, 2),
*discriminator_block(32, 64, 2),
*discriminator_block(64, 128, 2),
)
# Calculate the size after convolutions
ds_size = img_size // 2 ** 4
self.adv_layer = nn.Sequential(
nn.Linear(128 * ds_size ** 2, 1),
nn.Sigmoid()
)
def forward(self, img):
out = self.model(img)
out = out.view(out.shape[0], -1)
validity = self.adv_layer(out)
return validity
# ===================== DCGAN MODELS =====================
# ===================== DCGAN MODELS (DYNAMIC & IMPROVED) =====================
# ===================== DCGAN MODELS (DYNAMIC & IMPROVED) =====================
# ===================== DCGAN MODELS (DYNAMIC & IMPROVED) =====================
class Generator(nn.Module):
"""Powerful and FLEXIBLE DCGAN-style generator"""
def __init__(self, latent_dim=100, img_channels=3, img_size=64, feature_maps=64):
super().__init__()
# Calculate the number of upsampling blocks needed to go from 4x4 to img_size
num_blocks = int(np.log2(img_size) - 2)
if num_blocks < 1:
raise ValueError(f"Image size {img_size} is too small for this DCGAN architecture. Minimum is 8.")
layers = []
# Initial layer: from latent_dim to a 4x4 feature map
out_features = feature_maps * (2 ** (num_blocks - 1))
layers.extend([
nn.ConvTranspose2d(latent_dim, out_features, 4, 1, 0, bias=False),
nn.BatchNorm2d(out_features),
nn.ReLU(True)
])
# Upsampling blocks
for i in range(num_blocks - 1):
in_features = out_features
out_features = in_features // 2
layers.extend([
nn.ConvTranspose2d(in_features, out_features, 4, 2, 1, bias=False),
nn.BatchNorm2d(out_features),
nn.ReLU(True)
])
# Final layer: to img_size and target channels
layers.extend([
nn.ConvTranspose2d(out_features, img_channels, 4, 2, 1, bias=False),
nn.Tanh()
])
self.main = nn.Sequential(*layers)
def forward(self, z):
# Reshape z from (batch, latent_dim) to (batch, latent_dim, 1, 1)
z = z.view(z.shape[0], -1, 1, 1)
return self.main(z)
class Discriminator(nn.Module):
"""Powerful and FLEXIBLE DCGAN-style discriminator (Critic)"""
def __init__(self, img_channels=3, img_size=64, feature_maps=64):
super().__init__()
# Calculate the number of downsampling blocks
num_blocks = int(np.log2(img_size) - 2)
if num_blocks < 1:
raise ValueError(f"Image size {img_size} is too small for this DCGAN architecture. Minimum is 8.")
layers = []
# Initial layer
layers.extend([
nn.Conv2d(img_channels, feature_maps, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True)
])
in_features = feature_maps
# Downsampling blocks
for i in range(num_blocks - 1):
out_features = in_features * 2
layers.extend([
nn.Conv2d(in_features, out_features, 4, 2, 1, bias=False),
nn.InstanceNorm2d(out_features, affine=True),
nn.LeakyReLU(0.2, inplace=True)
])
in_features = out_features
# Final layer: downsample to a 1x1 feature map (a single score)
layers.extend([
nn.Conv2d(in_features, 1, 4, 1, 0, bias=False)
])
self.main = nn.Sequential(*layers)
def forward(self, img):
return self.main(img)
class Discriminator(nn.Module):
"""Powerful and FLEXIBLE DCGAN-style discriminator (Critic)"""
def __init__(self, img_channels=3, img_size=64, feature_maps=64):
super().__init__()
# Calculate the number of downsampling blocks
num_blocks = int(np.log2(img_size) - 2)
if num_blocks < 1:
raise ValueError(f"Image size {img_size} is too small for this DCGAN architecture. Minimum is 8.")
layers = []
# Initial layer
layers.extend([
nn.Conv2d(img_channels, feature_maps, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True)
])
in_features = feature_maps
# Downsampling blocks
for i in range(num_blocks - 1):
out_features = in_features * 2
layers.extend([
nn.Conv2d(in_features, out_features, 4, 2, 1, bias=False),
nn.InstanceNorm2d(out_features, affine=True),
nn.LeakyReLU(0.2, inplace=True)
])
in_features = out_features
# Final layer: downsample to a 1x1 feature map (a single score)
layers.extend([
nn.Conv2d(in_features, 1, 4, 1, 0, bias=False)
])
self.main = nn.Sequential(*layers)
def forward(self, img):
return self.main(img)
class Discriminator(nn.Module):
"""Powerful and FLEXIBLE DCGAN-style discriminator (Critic)"""
def __init__(self, img_channels=3, img_size=64, feature_maps=64):
super().__init__()
# Calculate the number of downsampling blocks
num_blocks = int(np.log2(img_size) - 2)
if num_blocks < 1:
raise ValueError(f"Image size {img_size} is too small for this DCGAN architecture. Minimum is 8.")
layers = []
# Initial layer
layers.extend([
nn.Conv2d(img_channels, feature_maps, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True)
])
in_features = feature_maps
# Downsampling blocks
for i in range(num_blocks - 1):
out_features = in_features * 2
layers.extend([
nn.Conv2d(in_features, out_features, 4, 2, 1, bias=False),
nn.InstanceNorm2d(out_features, affine=True),
nn.LeakyReLU(0.2, inplace=True)
])
in_features = out_features
# Final layer: downsample to a 1x1 feature map (a single score)
layers.extend([
nn.Conv2d(in_features, 1, 4, 1, 0, bias=False)
])
self.main = nn.Sequential(*layers)
def forward(self, img):
return self.main(img)
class Discriminator(nn.Module):
"""Powerful DCGAN-style discriminator (Critic)"""
def __init__(self, img_channels=3, feature_maps=64):
super().__init__()
self.main = nn.Sequential(
# Input size: (img_channels) x 64 x 64
nn.Conv2d(img_channels, feature_maps, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps) x 32 x 32
nn.Conv2d(feature_maps, feature_maps * 2, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 2, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*2) x 16 x 16
nn.Conv2d(feature_maps * 2, feature_maps * 4, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 4, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*4) x 8 x 8
nn.Conv2d(feature_maps * 4, feature_maps * 8, 4, 2, 1, bias=False),
nn.InstanceNorm2d(feature_maps * 8, affine=True),
nn.LeakyReLU(0.2, inplace=True),
# State size: (feature_maps*8) x 4 x 4
nn.Conv2d(feature_maps * 8, 1, 4, 1, 0, bias=False),
# Final output is a single raw score, not a probability
)
def forward(self, img):
return self.main(img)
class ImageDataset(Dataset):
"""Custom dataset for uploaded images"""
def __init__(self, images, transform=None, img_size=64):
self.images = images
self.transform = transform
self.img_size = img_size
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
image = self.images[idx]
# Resize image
image = image.resize((self.img_size, self.img_size), Image.Resampling.LANCZOS)
if self.transform:
image = self.transform(image)
return image
def preprocess_images(uploaded_files, img_size=64):
"""Preprocess uploaded images"""
images = []
valid_files = 0
progress_bar = st.progress(0, text="📄 Processing images...")
status_text = st.empty()
for idx, file in enumerate(uploaded_files):
try:
# Update progress with colorful text
progress_bar.progress((idx + 1) / len(uploaded_files),
text=f"🎨 Processing image {idx + 1}/{len(uploaded_files)}")
status_text.text(f"📸 Current: {file.name}")
image = Image.open(file)
# Convert to RGB if needed
if image.mode != 'RGB':
image = image.convert('RGB')
# Basic validation - check if image is too small
if image.size[0] < 16 or image.size[1] < 16:
st.warning(f"⚠️ Skipping {file.name}: image too small (minimum 16x16)")
continue
images.append(image)
valid_files += 1
except Exception as e:
st.error(f"❌ Could not process file {file.name}: {e}")
progress_bar.empty()
status_text.empty()
return images, valid_files
def compute_gradient_penalty(discriminator, real_samples, fake_samples):
"""Calculates the gradient penalty for WGAN-GP"""
alpha = torch.rand(real_samples.size(0), 1, 1, 1, device=device)
interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True)
d_interpolates = discriminator(interpolates)
fake = torch.ones(d_interpolates.size(), device=device, requires_grad=False)
gradients = torch.autograd.grad(
outputs=d_interpolates,
inputs=interpolates,
grad_outputs=fake,
create_graph=True,
retain_graph=True,
only_inputs=True,
)[0]
gradients = gradients.view(gradients.size(0), -1)
gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()
return gradient_penalty
def train_simple_gan(images, epochs=50, batch_size=4, lr=0.0002, latent_dim=100, img_size=64):
"""Train the Simple GAN with basic loss"""
# Data preparation
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
dataset = ImageDataset(images, transform=transform, img_size=img_size)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True)
if len(dataloader) == 0:
st.error(f"🚫 Cannot start training. The number of valid images ({len(dataset)}) is less than the batch size ({batch_size}). Please upload more images or reduce the batch size.")
return None, None, [], []
# Initialize networks
generator = SimpleGenerator(latent_dim=latent_dim, img_size=img_size).to(device)
discriminator = SimpleDiscriminator(img_size=img_size).to(device)
# Loss and optimizers
criterion = nn.BCELoss()
optimizer_G = optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.999))
optimizer_D = optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.999))
# Training progress containers with colorful headers
st.markdown("### 🎯 Training Progress Dashboard")
progress_bar = st.progress(0, text="🖼️ Starting training...")
col1, col2, col3 = st.columns(3)
with col1:
d_loss_metric = st.metric("🔴 Discriminator Loss", "0.0000")
with col2:
g_loss_metric = st.metric("🔵 Generator Loss", "0.0000")
with col3:
epoch_metric = st.metric("⏳ Current Epoch", "0")
loss_chart = st.empty()
sample_container = st.empty()
# Training history
d_losses = []
g_losses = []
# Training loop
for epoch in range(epochs):
epoch_d_loss = 0
epoch_g_loss = 0
batches = 0
for i, real_images in enumerate(dataloader):
batch_size_actual = real_images.size(0)
real_images = real_images.to(device)
# Labels
real_labels = torch.ones(batch_size_actual, 1, device=device)
fake_labels = torch.zeros(batch_size_actual, 1, device=device)
# Train Discriminator
optimizer_D.zero_grad()
# Real images
real_output = discriminator(real_images)
d_loss_real = criterion(real_output, real_labels)
# Fake images
z = torch.randn(batch_size_actual, latent_dim, device=device)
fake_images = generator(z)
fake_output = discriminator(fake_images.detach())
d_loss_fake = criterion(fake_output, fake_labels)
d_loss = (d_loss_real + d_loss_fake) / 2
d_loss.backward()
optimizer_D.step()
# Train Generator
optimizer_G.zero_grad()
fake_output = discriminator(fake_images)
g_loss = criterion(fake_output, real_labels)
g_loss.backward()
optimizer_G.step()
epoch_d_loss += d_loss.item()
epoch_g_loss += g_loss.item()
batches += 1
# Memory cleanup
del real_images, fake_images, z, real_output, fake_output
if i % 5 == 0: # Cleanup every 5 batches
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
if batches == 0:
st.warning(f"⚠️ Epoch {epoch+1}/{epochs} - No batches processed. Is number of images < batch size?")
continue
# Record losses
avg_d_loss = epoch_d_loss / batches
avg_g_loss = epoch_g_loss / batches
d_losses.append(avg_d_loss)
g_losses.append(avg_g_loss)
# Update progress and metrics with emojis
progress = (epoch + 1) / epochs
progress_bar.progress(progress, text=f"🎨 Training in progress... Epoch {epoch+1}/{epochs}")
d_loss_metric.metric("🔴 Discriminator Loss", f"{avg_d_loss:.4f}")
g_loss_metric.metric("🔵 Generator Loss", f"{avg_g_loss:.4f}")
epoch_metric.metric("⏳ Current Epoch", f"{epoch+1}/{epochs}")
# Update loss chart every 5 epochs with colorful styling
if (epoch + 1) % 5 == 0 or epoch == epochs - 1:
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(d_losses, label='🔴 Discriminator Loss', color='#ff6b6b', linewidth=2.5, alpha=0.8)
ax.plot(g_losses, label='🔵 Generator Loss', color='#4ecdc4', linewidth=2.5, alpha=0.8)
ax.set_xlabel('Epoch', fontsize=12, fontweight='bold')
ax.set_ylabel('Loss', fontsize=12, fontweight='bold')
ax.set_title('📈 Training Loss Curves', fontsize=14, fontweight='bold', pad=20)
ax.legend(fontsize=11)
ax.grid(True, alpha=0.3, linestyle='--')
ax.set_facecolor('#f8f9fa')
fig.patch.set_facecolor('white')
loss_chart.pyplot(fig)
plt.close(fig)
# Generate sample images every 10 epochs with better styling
if (epoch + 1) % 10 == 0 or epoch == epochs - 1:
with torch.no_grad():
sample_z = torch.randn(4, latent_dim, device=device)
sample_images = generator(sample_z)
sample_images = (sample_images + 1) / 2 # Denormalize
fig, axes = plt.subplots(1, 4, figsize=(14, 4))
fig.suptitle(f'🎨 Generated Images - Epoch {epoch+1}', fontsize=16, fontweight='bold', y=1.05)
for j in range(4):
img = sample_images[j].cpu().permute(1, 2, 0).numpy()
img = np.clip(img, 0, 1)
axes[j].imshow(img)
axes[j].axis('off')
axes[j].set_title(f'✨ Sample {j+1}', fontsize=12, pad=10)
# Add colorful border
for spine in axes[j].spines.values():
spine.set_edgecolor(['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4'][j])
spine.set_linewidth(3)
plt.tight_layout()
sample_container.pyplot(fig)
plt.close(fig)
del sample_z, sample_images
return generator, discriminator, d_losses, g_losses
def train_dcgan_wgan(images, epochs=50, batch_size=4, lr=0.0002, latent_dim=100, img_size=64):
"""Train the WGAN-GP with memory-efficient approach and data augmentation"""
if img_size != 64:
st.warning(f"⚠️ DCGAN-WGAN model is optimized for 64x64 images. Forcing resolution to 64px.")
img_size = 64
#st.warning(f"⚠️ DCGAN-WGAN model is optimized for 64x64 images. Forcing resolution to 64px.")
# 1. HEAVY DATA AUGMENTATION
# This is key for training on a small number of images
transform = transforms.Compose([
transforms.RandomResizedCrop(img_size, scale=(0.8, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
transforms.RandomRotation(15),
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
dataset = ImageDataset(images, transform=transform, img_size=img_size)
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, drop_last=True)
if len(dataloader) == 0:
st.error(f"🚫 Cannot start training. The number of valid images ({len(dataset)}) is less than the batch size ({batch_size}). Please upload more images or reduce the batch size.")
return None, None, [], []
# 2. UPDATED MODEL INITIALIZATION (PASSING IMG_SIZE)
# This now uses the flexible models which adapt to the image size
st.info(f"🖼️ Initializing DCGAN-WGAN model for {img_size}x{img_size} images...")
if img_size == 64:
generator = Generator(latent_dim=latent_dim, img_channels=3, feature_maps=64).to(device)
discriminator = Discriminator(img_channels=3, feature_maps=64).to(device)
elif img_size == 128:
generator = Generator128(latent_dim=latent_dim, img_channels=3, feature_maps=64).to(device)
discriminator = Discriminator128(latent_dim=latent_dim, img_channels=3, feature_maps=64).to(device)
else:
# This will handle 32px or any other unsupported sizes for this model
st.error(f"🚫 The DCGAN-WGAN model only supports 64x64 or 128x128 resolution.")
# WGAN-GP parameters
lambda_gp = 10
n_critic = 5 # Train discriminator more often than generator
# Use Adam optimizers with parameters recommended for WGAN
optimizer_G = optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.9))
optimizer_D = optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.9))
st.markdown("### 🎯 Training Progress Dashboard")
progress_bar = st.progress(0, text="🖼️ Starting training...")
col1, col2, col3 = st.columns(3)
with col1:
d_loss_metric = st.metric("🔴 Critic Loss", "0.00")
with col2:
g_loss_metric = st.metric("🔵 Generator Loss", "0.00")
with col3:
epoch_metric = st.metric("⏳ Current Epoch", "0")
loss_chart = st.empty()
sample_container = st.empty()
d_losses = []
g_losses = []
# 3. NEW WGAN-GP TRAINING LOOP
for epoch in range(epochs):
epoch_d_loss = 0
epoch_g_loss = 0
batches = 0
for i, real_images in enumerate(dataloader):
real_images = real_images.to(device)
batch_size_actual = real_images.size(0)
# ---------------------
# Train Discriminator (Critic)
# ---------------------
optimizer_D.zero_grad()
# Sample noise as generator input
z = torch.randn(batch_size_actual, latent_dim, device=device)
fake_images = generator(z)
# Real and fake images scores
real_validity = discriminator(real_images)
fake_validity = discriminator(fake_images.detach())
# Gradient penalty
gradient_penalty = compute_gradient_penalty(discriminator, real_images.data, fake_images.data)
# Critic loss
d_loss = -torch.mean(real_validity) + torch.mean(fake_validity) + lambda_gp * gradient_penalty
d_loss.backward()
optimizer_D.step()
epoch_d_loss += d_loss.item()
# Train the generator only every n_critic iterations
if i % n_critic == 0:
# -----------------
# Train Generator
# -----------------
optimizer_G.zero_grad()
# Generate a batch of images
# Reuse the z from the critic step for efficiency
gen_imgs = generator(z)
# Generator loss
g_loss = -torch.mean(discriminator(gen_imgs))
g_loss.backward()
optimizer_G.step()
epoch_g_loss += g_loss.item()
batches += 1
# Memory cleanup
del real_images, fake_images, z
if torch.cuda.is_available():
torch.cuda.empty_cache()
if batches == 0:
st.warning(f"⚠️ Epoch {epoch+1}/{epochs} - No batches processed.")
continue
avg_d_loss = epoch_d_loss / batches
avg_g_loss = epoch_g_loss / (batches / n_critic) if batches > 0 else 0
d_losses.append(avg_d_loss)
g_losses.append(avg_g_loss)
progress = (epoch + 1) / epochs
progress_bar.progress(progress, text=f"🎨 Training in progress... Epoch {epoch+1}/{epochs}")
d_loss_metric.metric("🔴 Critic Loss", f"{avg_d_loss:.2f}")
g_loss_metric.metric("🔵 Generator Loss", f"{avg_g_loss:.2f}")
epoch_metric.metric("⏳ Current Epoch", f"{epoch+1}/{epochs}")
# Update loss chart every 5 epochs with colorful styling
if (epoch + 1) % 5 == 0 or epoch == epochs - 1:
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(d_losses, label='🔴 Critic Loss', color='#ff6b6b', linewidth=2.5, alpha=0.8)
ax.plot(g_losses, label='🔵 Generator Loss', color='#4ecdc4', linewidth=2.5, alpha=0.8)
ax.set_xlabel('Epoch', fontsize=12, fontweight='bold')
ax.set_ylabel('Loss', fontsize=12, fontweight='bold')
ax.set_title('📈 Training Loss Curves', fontsize=14, fontweight='bold', pad=20)
ax.legend(fontsize=11)
ax.grid(True, alpha=0.3, linestyle='--')
ax.set_facecolor('#f8f9fa')
fig.patch.set_facecolor('white')
loss_chart.pyplot(fig)
plt.close(fig)
# Generate sample images every 10 epochs with better styling
if (epoch + 1) % 10 == 0 or epoch == epochs - 1:
with torch.no_grad():
sample_z = torch.randn(4, latent_dim, device=device)
sample_images = generator(sample_z)
sample_images = (sample_images + 1) / 2
fig, axes = plt.subplots(1, 4, figsize=(14, 4))
fig.suptitle(f'🎨 Generated Images - Epoch {epoch+1}', fontsize=16, fontweight='bold', y=1.05)
for j in range(4):
img = sample_images[j].cpu().permute(1, 2, 0).numpy()
img = np.clip(img, 0, 1)
axes[j].imshow(img)
axes[j].axis('off')
axes[j].set_title(f'✨ Sample {j+1}', fontsize=12, pad=10)
for spine in axes[j].spines.values():
spine.set_edgecolor(['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4'][j])
spine.set_linewidth(3)
plt.tight_layout()
sample_container.pyplot(fig)
plt.close(fig)
del sample_z, sample_images
return generator, discriminator, d_losses, g_losses
def generate_images(generator, num_images=8, latent_dim=100, is_simple=False):
"""Generate new images using trained generator"""
generator.eval()
with torch.no_grad():
z = torch.randn(num_images, latent_dim, device=device)
if not is_simple:
# For DCGAN, reshape z for ConvTranspose2d input
z = z.view(z.shape[0], -1, 1, 1)
generated_images = generator(z)
generated_images = (generated_images + 1) / 2 # Denormalize
# Create grid with better styling
rows = 2
cols = (num_images + 1) // rows
fig, axes = plt.subplots(rows, cols, figsize=(15, 8))
axes = axes.flatten()
colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff', '#5f27cd']
for i in range(num_images):
img = generated_images[i].cpu().permute(1, 2, 0).numpy()
img = np.clip(img, 0, 1)
axes[i].imshow(img)
axes[i].axis('off')
axes[i].set_title(f'✨ Generated #{i+1}', fontsize=11, fontweight='bold', pad=8)
# Add colorful border
for spine in axes[i].spines.values():
spine.set_edgecolor(colors[i % len(colors)])
spine.set_linewidth(3)
# Turn off unused subplots
for i in range(num_images, len(axes)):
axes[i].axis('off')
fig.suptitle('🎨 AI Generated Masterpieces', fontsize=18, fontweight='bold', y=0.98)
fig.patch.set_facecolor('white')
plt.tight_layout()
return fig
# ===================== DATABASE SETUP =====================
# Initialize TinyDB. This will create a db.json file in the same directory.
db = TinyDB('models_db.json')
def save_model_to_db(name, generator, model_type, latent_dim, img_size):
"""Saves a model's state_dict and metadata to TinyDB."""
st.info(f"💾 Saving model '{name}' to database...")
# Save model state_dict to an in-memory buffer
buffer = io.BytesIO()
torch.save(generator.state_dict(), buffer)
buffer.seek(0)
# Encode the binary data to a base64 string
model_b64 = base64.b64encode(buffer.read()).decode('utf-8')
# Create the document to insert into TinyDB
model_doc = {
"name": name,
"model_type": model_type,
"latent_dim": latent_dim,
"img_size": img_size,
"timestamp": str(datetime.datetime.now()),
"state_dict_b64": model_b64
}
# Insert or update the model by name
ModelQuery = Query()
db.upsert(model_doc, ModelQuery.name == name)
st.success(f"✅ Model '{name}' saved successfully!")
def load_model_from_db(name):
"""Loads a model's state_dict from TinyDB and reconstructs the model."""
st.info(f"🔍 Loading model '{name}' from database...")
# Find the model document
ModelQuery = Query()
model_doc = db.get(ModelQuery.name == name)
if not model_doc:
st.error(f"Model '{name}' not found in the database.")
return None, None
# Get metadata
model_type = model_doc['model_type']
latent_dim = model_doc['latent_dim']
img_size = model_doc['img_size']
# Instantiate the correct model architecture
if model_type == 'Simple GAN':
generator = SimpleGenerator(latent_dim=latent_dim, img_size=img_size).to(device)
elif model_type == 'DCGAN-WGAN':
if img_size == 128:
generator = Generator128(latent_dim=latent_dim).to(device)
else: # Default to 64px DCGAN
generator = Generator(latent_dim=latent_dim).to(device)
else:
st.error(f"Unknown model type: {model_type}")
return None, None
# Decode the base64 string back to binary data
model_b64 = model_doc['state_dict_b64']
model_bytes = base64.b64decode(model_b64.encode('utf-8'))