Prathm commited on
Commit
ee887f3
·
1 Parent(s): 05daa1d

Updated UI and added option for single image generation

Browse files
Files changed (4) hide show
  1. app.py +10 -261
  2. pages/Fusion Fashion.py +282 -0
  3. pages/Style One.py +256 -0
  4. pics/logo.jpeg +0 -0
app.py CHANGED
@@ -1,268 +1,17 @@
1
- import random
2
  import streamlit as st
3
- import torch
4
- import PIL
5
- import numpy as np
6
- from PIL import Image
7
- import imageio
8
- from models import get_instrumented_model
9
- from decomposition import get_or_compute
10
- from config import Config
11
- from skimage import img_as_ubyte
12
- import clip
13
- from torchvision.transforms import Resize, Normalize, Compose, CenterCrop
14
- from torch.optim import Adam
15
- from stqdm import stqdm
16
 
17
- torch.set_num_threads(8)
18
-
19
- # Speed up computation
20
- torch.autograd.set_grad_enabled(True)
21
- torch.backends.cudnn.benchmark = True
22
-
23
- # Specify model to use
24
- config = Config(
25
- model='StyleGAN2',
26
- layer='style',
27
- output_class= 'lookbook',
28
- components=80,
29
- use_w=True,
30
- batch_size=5_000, # style layer quite small
31
  )
32
 
33
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
34
-
35
- preprocess = Compose([
36
- Resize(224),
37
- CenterCrop(224),
38
- Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)),
39
- ])
40
-
41
- @st.cache_data
42
- def clip_optimized_latent(text, seed, iterations=25, lr=5e-2):
43
- seed = int(seed)
44
- text_input = clip.tokenize([text]).to(device)
45
-
46
- # Initialize a random latent vector
47
- latent_vector = model.sample_latent(1,seed=seed).detach().to(device)
48
- latent_vector.requires_grad = True
49
- latent_vector = [latent_vector]*model.get_max_latents()
50
- params = [torch.nn.Parameter(latent_vector[i], requires_grad=True) for i in range(len(latent_vector))]
51
- optimizer = Adam(params, lr=lr)
52
-
53
- with torch.no_grad():
54
- text_features = clip_model.encode_text(text_input)
55
-
56
- #pbar = tqdm(range(iterations), dynamic_ncols=True)
57
-
58
- for iteration in stqdm(range(iterations)):
59
- optimizer.zero_grad()
60
-
61
- # Generate an image from the latent vector
62
- image = model.sample(params)
63
- image = image.to(device)
64
-
65
- # Preprocess the image for the CLIP model
66
- image = preprocess(image)
67
- #image = clip_preprocess(Image.fromarray((image_np * 255).astype(np.uint8))).unsqueeze(0).to(device)
68
-
69
- # Extract features from the image
70
- image_features = clip_model.encode_image(image)
71
-
72
- # Calculate the loss and backpropagate
73
- loss = -torch.cosine_similarity(text_features, image_features).mean()
74
- loss.backward()
75
- optimizer.step()
76
-
77
- #pbar.set_description(f"Loss: {loss.item()}") # Update the progress bar to show the current loss
78
- print(f"Loss: {loss.item()}")
79
- w = [param.detach().cpu().numpy() for param in params]
80
-
81
- return w
82
-
83
- def mix_w(w1, w2, content, style):
84
- for i in range(0,5):
85
- w2[i] = w1[i] * (1 - content) + w2[i] * content
86
-
87
- for i in range(5, 16):
88
- w2[i] = w1[i] * (1 - style) + w2[i] * style
89
-
90
- return w2
91
-
92
- def display_sample_pytorch(seed, truncation, directions, distances, scale, start, end, w=None, disp=True, save=None, noise_spec=None):
93
- # blockPrint()
94
- model.truncation = truncation
95
- if w is None:
96
- w = model.sample_latent(1, seed=seed).detach().cpu().numpy()
97
- w = [w]*model.get_max_latents() # one per layer
98
- else:
99
- w_numpy = [x.cpu().detach().numpy() for x in w]
100
- w = [np.expand_dims(x, 0) for x in w_numpy]
101
- #w = [x.unsqueeze(0) for x in w]
102
-
103
-
104
- for l in range(start, end):
105
- for i in range(len(directions)):
106
- w[l] = w[l] + directions[i] * distances[i] * scale
107
-
108
- w = [torch.from_numpy(x).to(device) for x in w]
109
- torch.cuda.empty_cache()
110
- #save image and display
111
- out = model.sample(w)
112
- out = out.permute(0, 2, 3, 1).cpu().detach().numpy()
113
- out = np.clip(out, 0.0, 1.0).squeeze()
114
-
115
- final_im = Image.fromarray((out * 255).astype(np.uint8)).resize((500,500),Image.LANCZOS)
116
-
117
-
118
- if save is not None:
119
- if disp == False:
120
- print(save)
121
- final_im.save(f'out/{seed}_{save:05}.png')
122
- if disp:
123
- display(final_im)
124
-
125
- return final_im
126
-
127
- ## Generate image for app
128
- def generate_image(content, style, truncation, c0, c1, c2, c3, c4, c5, c6, start_layer, end_layer,w1,w2):
129
-
130
- scale = 1
131
- params = {'c0': c0,
132
- 'c1': c1,
133
- 'c2': c2,
134
- 'c3': c3,
135
- 'c4': c4,
136
- 'c5': c5,
137
- 'c6': c6}
138
-
139
- param_indexes = {'c0': 0,
140
- 'c1': 1,
141
- 'c2': 2,
142
- 'c3': 3,
143
- 'c4': 4,
144
- 'c5': 5,
145
- 'c6': 6}
146
-
147
- directions = []
148
- distances = []
149
- for k, v in params.items():
150
- directions.append(latent_dirs[param_indexes[k]])
151
- distances.append(v)
152
-
153
- if w1 is not None and w2 is not None:
154
- w1 = [torch.from_numpy(x).to(device) for x in w1]
155
- w2 = [torch.from_numpy(x).to(device) for x in w2]
156
-
157
-
158
- #w1 = clip_optimized_latent(text1, seed1, iters)
159
- im1 = model.sample(w1)
160
- im1_np = im1.permute(0, 2, 3, 1).cpu().detach().numpy()
161
- im1_np = np.clip(im1_np, 0.0, 1.0).squeeze()
162
-
163
- #w2 = clip_optimized_latent(text2, seed2, iters)
164
- im2 = model.sample(w2)
165
- im2_np = im2.permute(0, 2, 3, 1).cpu().detach().numpy()
166
- im2_np = np.clip(im2_np, 0.0, 1.0).squeeze()
167
-
168
- combined_im = np.concatenate([im1_np, im2_np], axis=1)
169
- input_im = Image.fromarray((combined_im * 255).astype(np.uint8))
170
-
171
-
172
- mixed_w = mix_w(w1, w2, content, style)
173
- return input_im, display_sample_pytorch(seed1, truncation, directions, distances, scale, int(start_layer), int(end_layer), w=mixed_w, disp=False)
174
-
175
-
176
- # Streamlit app title
177
- st.title("FashionGen Demo - AI assisted fashion design")
178
- """This application employs the StyleGAN framework, CLIP and GANSpace exploration techniques to synthesize images of garments from textual inputs. With training based on the comprehensive LookBook dataset, it supports an efficient fashion design process by transforming text into visual concepts, showcasing the practical application of Generative Adversarial Networks (GANs) in the realm of creative design."""
179
-
180
- @st.cache_resource
181
- def load_model():
182
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
183
- # Load the pre-trained CLIP model
184
- clip_model, clip_preprocess = clip.load("ViT-B/32", device=device)
185
- inst = get_instrumented_model(config.model, config.output_class,
186
- config.layer, device, use_w=config.use_w)
187
- return clip_model, inst
188
-
189
- # Then, to load your models, call this function:
190
- clip_model, inst = load_model()
191
- model = inst.model
192
-
193
- clip_model.eval()
194
- model.eval()
195
-
196
- path_to_components = get_or_compute(config, inst)
197
- comps = np.load(path_to_components)
198
- lst = comps.files
199
- latent_dirs = []
200
- latent_stdevs = []
201
-
202
- load_activations = False
203
-
204
- for item in lst:
205
- if load_activations:
206
- if item == 'act_comp':
207
- for i in range(comps[item].shape[0]):
208
- latent_dirs.append(comps[item][i])
209
- if item == 'act_stdev':
210
- for i in range(comps[item].shape[0]):
211
- latent_stdevs.append(comps[item][i])
212
- else:
213
- if item == 'lat_comp':
214
- for i in range(comps[item].shape[0]):
215
- latent_dirs.append(comps[item][i])
216
- if item == 'lat_stdev':
217
- for i in range(comps[item].shape[0]):
218
- latent_stdevs.append(comps[item][i])
219
-
220
- ## Side bar texts
221
- st.sidebar.title('Tuning Parameters')
222
- st.sidebar.subheader('(CLIP + GANSpace)')
223
-
224
-
225
- # Create UI widgets
226
- text1 = st.sidebar.text_input("Text Description 1")
227
- text2 = st.sidebar.text_input("Text Description 2")
228
- if 'seed1' not in st.session_state and 'seed2' not in st.session_state:
229
- st.session_state['seed1'] = random.randint(1, 1000)
230
- st.session_state['seed2'] = random.randint(1, 1000)
231
- seed1 = st.sidebar.number_input("Seed 1", value= st.session_state['seed1'])
232
- seed2 = st.sidebar.number_input("Seed 2", value= st.session_state['seed2'])
233
- st.session_state['seed1'] = seed1
234
- st.session_state['seed2'] = seed2
235
- iters = st.sidebar.number_input("Iterations for CLIP Optimization", value = 50)
236
- submit_button = st.sidebar.button("Submit")
237
- content = st.sidebar.slider("Structural Composition", min_value=0.0, max_value=1.0, value=0.5)
238
- style = st.sidebar.slider("Style", min_value=0.0, max_value=1.0, value=0.5)
239
- truncation = st.sidebar.slider("Dimensional Scaling", min_value=0.0, max_value=1.0, value=0.5)
240
-
241
- slider_min_val = -20
242
- slider_max_val = 20
243
- slider_step = 1
244
-
245
- c0 = st.sidebar.slider("Sleeve Size Scaling", min_value=slider_min_val, max_value=slider_max_val, value=0)
246
- c1 = st.sidebar.slider("Jacket Features", min_value=slider_min_val, max_value=slider_max_val, value=0)
247
- c2 = st.sidebar.slider("Women's Overcoat", min_value=slider_min_val, max_value=slider_max_val, value=0)
248
- c3 = st.sidebar.slider("Coat", min_value=slider_min_val, max_value=slider_max_val, value=0)
249
- c4 = st.sidebar.slider("Graphic Elements", min_value=slider_min_val, max_value=slider_max_val, value=0)
250
- c5 = st.sidebar.slider("Darker Color", min_value=slider_min_val, max_value=slider_max_val, value=0)
251
- c6 = st.sidebar.slider("Modest Neckline", min_value=slider_min_val, max_value=slider_max_val, value=0)
252
- start_layer = st.sidebar.number_input("Start Layer", value=0)
253
- end_layer = st.sidebar.number_input("End Layer", value=14)
254
-
255
 
 
 
 
256
 
257
- if submit_button: # Execute when the submit button is pressed
258
- w1 = clip_optimized_latent(text1, seed1, iters)
259
- st.session_state['w1-np'] = w1
260
- w2 = clip_optimized_latent(text2, seed2, iters)
261
- st.session_state['w2-np'] = w2
262
 
263
- try:
264
- input_im, output_im = generate_image(content, style, truncation, c0, c1, c2, c3, c4, c5, c6, start_layer, end_layer,st.session_state['w1-np'],st.session_state['w2-np'])
265
- st.image(input_im, caption="Input Image")
266
- st.image(output_im, caption="Output Image")
267
- except:
268
- pass
 
 
1
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ st.set_page_config(
4
+ page_title="FashionGen",
5
+ page_icon="👗",
 
 
 
 
 
 
 
 
 
 
 
6
  )
7
 
8
+ #st.title("FashionGen")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ st.image('./pics/logo.jpeg')
11
+ '''#### About:'''
12
+ '''This application employs the StyleGAN framework, CLIP and GANSpace exploration techniques to synthesize images of garments from textual inputs. With training based on the comprehensive LookBook dataset, it supports an efficient fashion design process by transforming text into visual concepts, showcasing the practical application of Generative Adversarial Networks (GANs) in the realm of creative design.'''
13
 
 
 
 
 
 
14
 
15
+ ''' There are two modes of image generatation: \n
16
+ **Fashion Fusion:** Takes two descriptions and generates two designs whose styles features can be combined and edited. \n
17
+ **Style One:** Takes a single description and generates one design whose style features can be edited.'''
 
 
 
pages/Fusion Fashion.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import streamlit as st
3
+ import torch
4
+ import PIL
5
+ import numpy as np
6
+ from PIL import Image
7
+ import imageio
8
+ from models import get_instrumented_model
9
+ from decomposition import get_or_compute
10
+ from config import Config
11
+ from skimage import img_as_ubyte
12
+ import clip
13
+ from torchvision.transforms import Resize, Normalize, Compose, CenterCrop
14
+ from torch.optim import Adam
15
+ from stqdm import stqdm
16
+
17
+
18
+ st.set_page_config(
19
+ page_title="Fusion Fashion",
20
+ page_icon="👗",
21
+ )
22
+
23
+ #torch.set_num_threads(8)
24
+
25
+ # Speed up computation
26
+ torch.autograd.set_grad_enabled(True)
27
+ torch.backends.cudnn.benchmark = True
28
+
29
+ # Specify model to use
30
+ config = Config(
31
+ model='StyleGAN2',
32
+ layer='style',
33
+ output_class= 'lookbook',
34
+ components=80,
35
+ use_w=True,
36
+ batch_size=5_000, # style layer quite small
37
+ )
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+
41
+ preprocess = Compose([
42
+ Resize(224),
43
+ CenterCrop(224),
44
+ Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)),
45
+ ])
46
+
47
+ @st.cache_data
48
+ def clip_optimized_latent(text, seed, iterations=25, lr=1e-2):
49
+ seed = int(seed)
50
+ text_input = clip.tokenize([text]).to(device)
51
+
52
+ # Initialize a random latent vector
53
+ latent_vector = model.sample_latent(1,seed=seed).detach().to(device)
54
+ latent_vector.requires_grad = True
55
+ latent_vector = [latent_vector]*model.get_max_latents()
56
+ params = [torch.nn.Parameter(latent_vector[i], requires_grad=True) for i in range(len(latent_vector))]
57
+ optimizer = Adam(params, lr=lr, betas=(0.9, 0.999))
58
+
59
+ #with torch.no_grad():
60
+ # text_features = clip_model.encode_text(text_input)
61
+
62
+ #pbar = tqdm(range(iterations), dynamic_ncols=True)
63
+
64
+ for iteration in stqdm(range(iterations)):
65
+ optimizer.zero_grad()
66
+
67
+ # Generate an image from the latent vector
68
+ image = model.sample(params)
69
+ image = image.to(device)
70
+
71
+ # Preprocess the image for the CLIP model
72
+ image = preprocess(image)
73
+ #image = clip_preprocess(Image.fromarray((image_np * 255).astype(np.uint8))).unsqueeze(0).to(device)
74
+
75
+ # Extract features from the image
76
+ #image_features = clip_model.encode_image(image)
77
+
78
+ # Calculate the loss and backpropagate
79
+ loss = 1 - clip_model(image, text_input)[0] / 100
80
+ #loss = -torch.cosine_similarity(text_features, image_features).mean()
81
+ loss.backward()
82
+ optimizer.step()
83
+
84
+ #pbar.set_description(f"Loss: {loss.item()}") # Update the progress bar to show the current loss
85
+ w = [param.detach().cpu().numpy() for param in params]
86
+
87
+ return w
88
+
89
+ def mix_w(w1, w2, content, style):
90
+ for i in range(0,5):
91
+ w2[i] = w1[i] * (1 - content) + w2[i] * content
92
+
93
+ for i in range(5, 16):
94
+ w2[i] = w1[i] * (1 - style) + w2[i] * style
95
+
96
+ return w2
97
+
98
+ def display_sample_pytorch(seed, truncation, directions, distances, scale, start, end, w=None, disp=True, save=None, noise_spec=None):
99
+ # blockPrint()
100
+ model.truncation = truncation
101
+ if w is None:
102
+ w = model.sample_latent(1, seed=seed).detach().cpu().numpy()
103
+ w = [w]*model.get_max_latents() # one per layer
104
+ else:
105
+ w_numpy = [x.cpu().detach().numpy() for x in w]
106
+ w = [np.expand_dims(x, 0) for x in w_numpy]
107
+ #w = [x.unsqueeze(0) for x in w]
108
+
109
+
110
+ for l in range(start, end):
111
+ for i in range(len(directions)):
112
+ w[l] = w[l] + directions[i] * distances[i] * scale
113
+
114
+ w = [torch.from_numpy(x).to(device) for x in w]
115
+ torch.cuda.empty_cache()
116
+ #save image and display
117
+ out = model.sample(w)
118
+ out = out.permute(0, 2, 3, 1).cpu().detach().numpy()
119
+ out = np.clip(out, 0.0, 1.0).squeeze()
120
+
121
+ final_im = Image.fromarray((out * 255).astype(np.uint8)).resize((500,500),Image.LANCZOS)
122
+
123
+
124
+ if save is not None:
125
+ if disp == False:
126
+ print(save)
127
+ final_im.save(f'out/{seed}_{save:05}.png')
128
+ if disp:
129
+ display(final_im)
130
+
131
+ return final_im
132
+
133
+ ## Generate image for app
134
+ def generate_image(content, style, truncation, c0, c1, c2, c3, c4, c5, c6, start_layer, end_layer,w1,w2):
135
+
136
+ scale = 1
137
+ params = {'c0': c0,
138
+ 'c1': c1,
139
+ 'c2': c2,
140
+ 'c3': c3,
141
+ 'c4': c4,
142
+ 'c5': c5,
143
+ 'c6': c6}
144
+
145
+ param_indexes = {'c0': 0,
146
+ 'c1': 1,
147
+ 'c2': 2,
148
+ 'c3': 3,
149
+ 'c4': 4,
150
+ 'c5': 5,
151
+ 'c6': 6}
152
+
153
+ directions = []
154
+ distances = []
155
+ for k, v in params.items():
156
+ directions.append(latent_dirs[param_indexes[k]])
157
+ distances.append(v)
158
+
159
+ if w1 is not None and w2 is not None:
160
+ w1 = [torch.from_numpy(x).to(device) for x in w1]
161
+ w2 = [torch.from_numpy(x).to(device) for x in w2]
162
+
163
+
164
+ #w1 = clip_optimized_latent(text1, seed1, iters)
165
+ im1 = model.sample(w1)
166
+ im1_np = im1.permute(0, 2, 3, 1).cpu().detach().numpy()
167
+ im1_np = np.clip(im1_np, 0.0, 1.0).squeeze()
168
+
169
+ #w2 = clip_optimized_latent(text2, seed2, iters)
170
+ im2 = model.sample(w2)
171
+ im2_np = im2.permute(0, 2, 3, 1).cpu().detach().numpy()
172
+ im2_np = np.clip(im2_np, 0.0, 1.0).squeeze()
173
+
174
+ combined_im = np.concatenate([im1_np, im2_np], axis=1)
175
+ input_im = Image.fromarray((combined_im * 255).astype(np.uint8))
176
+
177
+
178
+ mixed_w = mix_w(w1, w2, content, style)
179
+ return input_im, display_sample_pytorch(seed1, truncation, directions, distances, scale, int(start_layer), int(end_layer), w=mixed_w, disp=False)
180
+
181
+
182
+ # Streamlit app title
183
+ st.title("Fusion Fashion")
184
+
185
+ @st.cache_resource
186
+ def load_model():
187
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
188
+ # Load the pre-trained CLIP model
189
+ clip_model, clip_preprocess = clip.load("ViT-B/32", device=device)
190
+ inst = get_instrumented_model(config.model, config.output_class,
191
+ config.layer, device, use_w=config.use_w)
192
+ return clip_model, inst
193
+
194
+ # Then, to load your models, call this function:
195
+ clip_model, inst = load_model()
196
+ model = inst.model
197
+
198
+
199
+ path_to_components = get_or_compute(config, inst)
200
+ comps = np.load(path_to_components)
201
+ lst = comps.files
202
+ latent_dirs = []
203
+ latent_stdevs = []
204
+
205
+ load_activations = False
206
+
207
+ for item in lst:
208
+ if load_activations:
209
+ if item == 'act_comp':
210
+ for i in range(comps[item].shape[0]):
211
+ latent_dirs.append(comps[item][i])
212
+ if item == 'act_stdev':
213
+ for i in range(comps[item].shape[0]):
214
+ latent_stdevs.append(comps[item][i])
215
+ else:
216
+ if item == 'lat_comp':
217
+ for i in range(comps[item].shape[0]):
218
+ latent_dirs.append(comps[item][i])
219
+ if item == 'lat_stdev':
220
+ for i in range(comps[item].shape[0]):
221
+ latent_stdevs.append(comps[item][i])
222
+
223
+ ## Side bar texts
224
+ st.sidebar.title('Customization Options')
225
+
226
+
227
+ # Create UI widgets
228
+ text1 = st.sidebar.text_input("Style Specs 1", help = "Provide a clear and concise description of the design you wish to generate. This helps the app understand your preferences and create a customized design that matches your vision.")
229
+ text2 = st.sidebar.text_input("Style Specs 2", help = "Provide a clear and concise description of the design you wish to generate. This helps the app understand your preferences and create a customized design that matches your vision.")
230
+ if 'seed1' not in st.session_state and 'seed2' not in st.session_state:
231
+ st.session_state['seed1'] = random.randint(1, 1000)
232
+ st.session_state['seed2'] = random.randint(1, 1000)
233
+
234
+ with st.sidebar.expander("Advanced"):
235
+ seed1 = st.number_input("ID 1", value= st.session_state['seed1'], help = "Capture this unique id to reproduce the exact same result later.")
236
+ seed2 = st.number_input("ID 2", value= st.session_state['seed2'], help = "Capture this unique id to reproduce the exact same result later.")
237
+
238
+ st.session_state['seed1'] = seed1
239
+ st.session_state['seed2'] = seed2
240
+ iters = st.number_input("Cycles", value = 25, help = "Increase the sensitivity of the algorithm to find the design matching the style description. Higher values might enhance the accuracy but may lead to slower loading times")
241
+
242
+ submit_button = st.sidebar.button("Discover")
243
+ content = st.sidebar.slider("Design Frame", min_value=0.0, max_value=1.0, value=0.5, help = "Increasing it makes the structure similar to the image on the right and decreasing it will make the structure similar to the image on the left")
244
+ style = st.sidebar.slider("Style Composition", min_value=0.0, max_value=1.0, value=0.5, help = "Increasing it makes the style/pattern similar to the image on the right and decreasing it will make the style/pattern similar to the image on the left")
245
+ truncation = 0.5
246
+ #truncation = st.sidebar.slider("Dimensional Scaling", min_value=0.0, max_value=1.0, value=0.5)
247
+
248
+ slider_min_val = -20
249
+ slider_max_val = 20
250
+ slider_step = 1
251
+
252
+ c0 = st.sidebar.slider("Sleeve Size Scaling", min_value=slider_min_val, max_value=slider_max_val, value=0, help="Adjust the scaling of sleeve sizes. Increase to make sleeve sizes appear larger, and decrease to make them appear smaller.")
253
+ c1 = st.sidebar.slider("Jacket Features", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Control the prominence of jacket features. Increasing this value will make the features more pronounced, while decreasing it will make them less noticeable")
254
+ c2 = st.sidebar.slider("Women's Overcoat", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Modify the dominance of the women's overcoat style. Increase the value to enhance its prominence, and decrease it to reduce its impact.")
255
+ c3 = st.sidebar.slider("Coat", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Control the prominence of coat features. Increasing this value will make the features more pronounced, while decreasing it will make them less noticeable")
256
+ c4 = st.sidebar.slider("Graphic Elements", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Fine-tune the visibility of graphic elements. Increasing this value will make the graphics more prominent, while decreasing it will make them less visible.")
257
+ c5 = st.sidebar.slider("Darker Color", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Adjust the intensity of the color tones towards darker shades. Increasing this value will make the colors appear deeper, while decreasing it will lighten the overall color palette.")
258
+ c6 = st.sidebar.slider("Neckline", min_value=slider_min_val, max_value=slider_max_val, value=0,help = "Control the emphasis on the neckline of the garment. Increase to highlight the neckline, and decrease to downplay its prominence.")
259
+ start_layer = 0
260
+ end_layer = 14
261
+ #start_layer = st.sidebar.number_input("Start Layer", value=0)
262
+ #end_layer = st.sidebar.number_input("End Layer", value=14)
263
+
264
+ # if 'w1-np' not in st.session_state:
265
+ # st.session_state['w1-np'] = None
266
+
267
+ # if 'w2-np' not in st.session_state:
268
+ # st.session_state['w2-np'] = None
269
+
270
+
271
+ if submit_button: # Execute when the submit button is pressed
272
+ w1 = clip_optimized_latent(text1, seed1, iters)
273
+ st.session_state['w1-np'] = w1
274
+ w2 = clip_optimized_latent(text2, seed2, iters)
275
+ st.session_state['w2-np'] = w2
276
+
277
+ try:
278
+ input_im, output_im = generate_image(content, style, truncation, c0, c1, c2, c3, c4, c5, c6, start_layer, end_layer,st.session_state['w1-np'],st.session_state['w2-np'])
279
+ st.image(input_im, caption="Input Image")
280
+ st.image(output_im, caption="Output Image")
281
+ except:
282
+ pass
pages/Style One.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import streamlit as st
3
+ import torch
4
+ import PIL
5
+ import numpy as np
6
+ from PIL import Image
7
+ import imageio
8
+ from models import get_instrumented_model
9
+ from decomposition import get_or_compute
10
+ from config import Config
11
+ from skimage import img_as_ubyte
12
+ import clip
13
+ from torchvision.transforms import Resize, Normalize, Compose, CenterCrop
14
+ from torch.optim import Adam
15
+ from stqdm import stqdm
16
+
17
+
18
+ st.set_page_config(
19
+ page_title="Style One",
20
+ page_icon="👗",
21
+ )
22
+
23
+ #torch.set_num_threads(8)
24
+
25
+ # Speed up computation
26
+ torch.autograd.set_grad_enabled(True)
27
+ torch.backends.cudnn.benchmark = True
28
+
29
+ # Specify model to use
30
+ config = Config(
31
+ model='StyleGAN2',
32
+ layer='style',
33
+ output_class= 'lookbook',
34
+ components=80,
35
+ use_w=True,
36
+ batch_size=5_000, # style layer quite small
37
+ )
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+
41
+ preprocess = Compose([
42
+ Resize(224),
43
+ CenterCrop(224),
44
+ Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)),
45
+ ])
46
+
47
+ @st.cache_data
48
+ def clip_optimized_latent(text, seed, iterations=25, lr=1e-2):
49
+ seed = int(seed)
50
+ text_input = clip.tokenize([text]).to(device)
51
+
52
+ # Initialize a random latent vector
53
+ latent_vector = model.sample_latent(1,seed=seed).detach().to(device)
54
+ latent_vector.requires_grad = True
55
+ latent_vector = [latent_vector]*model.get_max_latents()
56
+ params = [torch.nn.Parameter(latent_vector[i], requires_grad=True) for i in range(len(latent_vector))]
57
+ optimizer = Adam(params, lr=lr, betas=(0.9, 0.999))
58
+
59
+ #with torch.no_grad():
60
+ # text_features = clip_model.encode_text(text_input)
61
+
62
+ #pbar = tqdm(range(iterations), dynamic_ncols=True)
63
+
64
+ for iteration in stqdm(range(iterations)):
65
+ optimizer.zero_grad()
66
+
67
+ # Generate an image from the latent vector
68
+ image = model.sample(params)
69
+ image = image.to(device)
70
+
71
+ # Preprocess the image for the CLIP model
72
+ image = preprocess(image)
73
+ #image = clip_preprocess(Image.fromarray((image_np * 255).astype(np.uint8))).unsqueeze(0).to(device)
74
+
75
+ # Extract features from the image
76
+ #image_features = clip_model.encode_image(image)
77
+
78
+ # Calculate the loss and backpropagate
79
+ loss = 1 - clip_model(image, text_input)[0] / 100
80
+ #loss = -torch.cosine_similarity(text_features, image_features).mean()
81
+ loss.backward()
82
+ optimizer.step()
83
+
84
+ #pbar.set_description(f"Loss: {loss.item()}") # Update the progress bar to show the current loss
85
+ w = [param.detach().cpu().numpy() for param in params]
86
+
87
+ return w
88
+
89
+
90
+ def display_sample_pytorch(seed, truncation, directions, distances, scale, start, end, w=None, disp=True, save=None, noise_spec=None):
91
+ # blockPrint()
92
+ model.truncation = truncation
93
+ if w is None:
94
+ w = model.sample_latent(1, seed=seed).detach().cpu().numpy()
95
+ w = [w]*model.get_max_latents() # one per layer
96
+ else:
97
+ w_numpy = [x.cpu().detach().numpy() for x in w]
98
+ w = [np.expand_dims(x, 0) for x in w_numpy]
99
+ #w = [x.unsqueeze(0) for x in w]
100
+
101
+
102
+ for l in range(start, end):
103
+ for i in range(len(directions)):
104
+ w[l] = w[l] + directions[i] * distances[i] * scale
105
+
106
+ w = [torch.from_numpy(x).to(device) for x in w]
107
+ torch.cuda.empty_cache()
108
+ #save image and display
109
+ out = model.sample(w)
110
+ out = out.permute(0, 2, 3, 1).cpu().detach().numpy()
111
+ out = np.clip(out, 0.0, 1.0).squeeze()
112
+
113
+ final_im = Image.fromarray((out * 255).astype(np.uint8)).resize((500,500),Image.LANCZOS)
114
+
115
+
116
+ if save is not None:
117
+ if disp == False:
118
+ print(save)
119
+ final_im.save(f'out/{seed}_{save:05}.png')
120
+ if disp:
121
+ display(final_im)
122
+
123
+ return final_im
124
+
125
+ ## Generate image for app
126
+ def generate_image(truncation, c0, c1, c2, c3, c4, c5, c6, start_layer, end_layer,w):
127
+
128
+ scale = 1
129
+ params = {'c0': c0,
130
+ 'c1': c1,
131
+ 'c2': c2,
132
+ 'c3': c3,
133
+ 'c4': c4,
134
+ 'c5': c5,
135
+ 'c6': c6}
136
+
137
+ param_indexes = {'c0': 0,
138
+ 'c1': 1,
139
+ 'c2': 2,
140
+ 'c3': 3,
141
+ 'c4': 4,
142
+ 'c5': 5,
143
+ 'c6': 6}
144
+
145
+ directions = []
146
+ distances = []
147
+ for k, v in params.items():
148
+ directions.append(latent_dirs[param_indexes[k]])
149
+ distances.append(v)
150
+
151
+ if w is not None:
152
+ w = [torch.from_numpy(x).to(device) for x in w]
153
+
154
+ #w1 = clip_optimized_latent(text1, seed1, iters)
155
+ im = model.sample(w)
156
+ im_np = im.permute(0, 2, 3, 1).cpu().detach().numpy()
157
+ im_np = np.clip(im_np, 0.0, 1.0).squeeze()
158
+
159
+
160
+ input_im = Image.fromarray((im_np * 255).astype(np.uint8))
161
+ seed = 0
162
+
163
+ return input_im, display_sample_pytorch(seed, truncation, directions, distances, scale, int(start_layer), int(end_layer), w=w, disp=False)
164
+
165
+
166
+ # Streamlit app title
167
+ st.title("Style One")
168
+
169
+ @st.cache_resource
170
+ def load_model():
171
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
172
+ # Load the pre-trained CLIP model
173
+ clip_model, clip_preprocess = clip.load("ViT-B/32", device=device)
174
+ inst = get_instrumented_model(config.model, config.output_class,
175
+ config.layer, device, use_w=config.use_w)
176
+ return clip_model, inst
177
+
178
+ # Then, to load your models, call this function:
179
+ clip_model, inst = load_model()
180
+ model = inst.model
181
+
182
+
183
+ path_to_components = get_or_compute(config, inst)
184
+ comps = np.load(path_to_components)
185
+ lst = comps.files
186
+ latent_dirs = []
187
+ latent_stdevs = []
188
+
189
+ load_activations = False
190
+
191
+ for item in lst:
192
+ if load_activations:
193
+ if item == 'act_comp':
194
+ for i in range(comps[item].shape[0]):
195
+ latent_dirs.append(comps[item][i])
196
+ if item == 'act_stdev':
197
+ for i in range(comps[item].shape[0]):
198
+ latent_stdevs.append(comps[item][i])
199
+ else:
200
+ if item == 'lat_comp':
201
+ for i in range(comps[item].shape[0]):
202
+ latent_dirs.append(comps[item][i])
203
+ if item == 'lat_stdev':
204
+ for i in range(comps[item].shape[0]):
205
+ latent_stdevs.append(comps[item][i])
206
+
207
+ ## Side bar texts
208
+ st.sidebar.title('Customization Options')
209
+
210
+
211
+ # Create UI widgets
212
+ text = st.sidebar.text_input("Style Specs", help = "Provide a clear and concise description of the design you wish to generate. This helps the app understand your preferences and create a customized design that matches your vision.")
213
+ if 'seed' not in st.session_state:
214
+ st.session_state['seed'] = random.randint(1, 1000)
215
+
216
+ with st.sidebar.expander("Advanced"):
217
+ seed = st.number_input("ID", value= st.session_state['seed'], help = "Capture this unique id to reproduce the exact same result later.")
218
+
219
+ st.session_state['seed'] = seed
220
+ iters = st.number_input("Cycles", value = 25, help = "Increase the sensitivity of the algorithm to find the design matching the style description. Higher values might enhance the accuracy but may lead to slower loading times")
221
+ submit_button = st.sidebar.button("Discover")
222
+ # content = st.sidebar.slider("Structural Composition", min_value=0.0, max_value=1.0, value=0.5)
223
+ # style = st.sidebar.slider("Style", min_value=0.0, max_value=1.0, value=0.5)
224
+ truncation = 0.5
225
+ #truncation = st.sidebar.slider("Dimensional Scaling", min_value=0.0, max_value=1.0, value=0.5)
226
+
227
+ slider_min_val = -20
228
+ slider_max_val = 20
229
+ slider_step = 1
230
+
231
+ c0 = st.sidebar.slider("Sleeve Size Scaling", min_value=slider_min_val, max_value=slider_max_val, value=0, help="Adjust the scaling of sleeve sizes. Increase to make sleeve sizes appear larger, and decrease to make them appear smaller.")
232
+ c1 = st.sidebar.slider("Jacket Features", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Control the prominence of jacket features. Increasing this value will make the features more pronounced, while decreasing it will make them less noticeable")
233
+ c2 = st.sidebar.slider("Women's Overcoat", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Modify the dominance of the women's overcoat style. Increase the value to enhance its prominence, and decrease it to reduce its impact.")
234
+ c3 = st.sidebar.slider("Coat", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Control the prominence of coat features. Increasing this value will make the features more pronounced, while decreasing it will make them less noticeable")
235
+ c4 = st.sidebar.slider("Graphic Elements", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Fine-tune the visibility of graphic elements. Increasing this value will make the graphics more prominent, while decreasing it will make them less visible.")
236
+ c5 = st.sidebar.slider("Darker Color", min_value=slider_min_val, max_value=slider_max_val, value=0, help = "Adjust the intensity of the color tones towards darker shades. Increasing this value will make the colors appear deeper, while decreasing it will lighten the overall color palette.")
237
+ c6 = st.sidebar.slider("Neckline", min_value=slider_min_val, max_value=slider_max_val, value=0,help = "Control the emphasis on the neckline of the garment. Increase to highlight the neckline, and decrease to downplay its prominence.")
238
+ start_layer = 0
239
+ end_layer = 14
240
+ #start_layer = st.sidebar.number_input("Start Layer", value=0)
241
+ #end_layer = st.sidebar.number_input("End Layer", value=14)
242
+
243
+ # if 'w-np' not in st.session_state:
244
+ # st.session_state['w-np'] = None
245
+
246
+ if submit_button: # Execute when the submit button is pressed
247
+ w = clip_optimized_latent(text, seed, iters)
248
+ st.session_state['w-np'] = w
249
+
250
+
251
+ try:
252
+ input_im, output_im = generate_image(truncation, c0, c1, c2, c3, c4, c5, c6, start_layer, end_layer,st.session_state['w-np'])
253
+ st.image(input_im, caption="Input Image")
254
+ st.image(output_im, caption="Output Image")
255
+ except:
256
+ pass
pics/logo.jpeg ADDED