File size: 12,955 Bytes
5d4f45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101cf83
4332791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c6e97
 
 
 
 
be7fb10
 
5d4f45d
e1ed2a7
 
1dc81a4
e1ed2a7
 
1dc81a4
 
 
 
 
fcea2d8
1dc81a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4c9991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dc81a4
34c6e97
a4c9991
 
34c6e97
a4c9991
 
34c6e97
 
 
 
 
 
 
 
 
 
 
 
 
 
a4c9991
1dc81a4
4332791
e1ed2a7
34c6e97
e1ed2a7
 
 
 
 
 
 
 
 
4332791
0331cd5
 
be7fb10
ba33c62
 
0331cd5
 
ba33c62
27e43e3
4332791
27e43e3
 
ba33c62
157aa00
be7fb10
0331cd5
 
 
 
 
 
 
 
 
 
27e43e3
4332791
949376a
 
be7fb10
949376a
 
 
 
0331cd5
949376a
0331cd5
949376a
 
 
0331cd5
949376a
0331cd5
949376a
 
 
0331cd5
949376a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be7fb10
0331cd5
949376a
 
 
 
 
 
 
 
 
 
 
 
 
f489b31
 
949376a
 
 
 
 
f489b31
949376a
 
 
 
 
 
0331cd5
 
 
 
949376a
 
 
 
 
 
 
 
 
 
 
 
0331cd5
101cf83
e86172c
949376a
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
# import gradio as gr
# import torch
# import numpy as np
# from PIL import Image
# import os
# import legacy
# import torch_utils

# # Load the pre-trained StyleGAN model
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# model_path = 'dress_model.pkl'  # Place your .pkl in the same directory or update path

# # Load StyleGAN Generator
# with open(model_path, 'rb') as f:
#     G = legacy.load_network_pkl(f)['G_ema'].to(device)

# def mix_styles(image1_path, image2_path, styles_to_mix):
#     # Extract image names (without extensions)
#     image1_name = os.path.splitext(os.path.basename(image1_path))[0]
#     image2_name = os.path.splitext(os.path.basename(image2_path))[0]

#     # Load latent vectors from .npz
#     latent_vector_1 = np.load(os.path.join("projection_results", image1_name, "projected_w.npz"))['w']
#     latent_vector_2 = np.load(os.path.join("projection_results", image2_name, "projected_w.npz"))['w']

#     # Convert to torch tensors
#     latent_1_tensor = torch.from_numpy(latent_vector_1).to(device)
#     latent_2_tensor = torch.from_numpy(latent_vector_2).to(device)

#     # Mix layers
#     mixed_latent = latent_1_tensor.clone()
#     mixed_latent[:, styles_to_mix] = latent_2_tensor[:, styles_to_mix]

#     # Generate image
#     with torch.no_grad():
#         image = G.synthesis(mixed_latent, noise_mode='const')

#     # Convert to image
#     image = (image.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy()
#     mixed_image = Image.fromarray(image[0], 'RGB')
#     return mixed_image

# def style_mixing_interface(image1, image2, mix_value):
#     if image1 is None or image2 is None:
#         return None
#     selected_layers = list(range(mix_value + 1))
#     return mix_styles(image1, image2, selected_layers)

# # Gradio UI
# iface = gr.Interface(
#     fn=style_mixing_interface,
#     inputs=[
#         gr.Image(label="First Clothing Image", type="filepath"),
#         gr.Image(label="Second Clothing Image", type="filepath"),
#         gr.Slider(label="Style Mixing Strength (Layers 0 to N)", minimum=0, maximum=9, step=1, value=5)
#     ],
#     outputs=gr.Image(label="Mixed Clothing Design"),
#     live=True,
#     title="Style Mixing for Clothing Design",
#     description="Upload two projected images and choose how many early layers to mix."
# )


# iface.launch()







# import gradio as gr
# import torch
# import numpy as np
# from PIL import Image
# import os
# import legacy
# import torch_utils
# import requests
# import io
# import warnings

# warnings.filterwarnings("ignore")
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# model_path = 'dress_model.pkl'
# with open(model_path, 'rb') as f:
#     G = legacy.load_network_pkl(f)['G_ema'].to(device)

# def mix_styles(image1_path, image2_path, styles_to_mix):
#     image1_name = os.path.splitext(os.path.basename(image1_path))[0]
#     image2_name = os.path.splitext(os.path.basename(image2_path))[0]

#     latent_vector_1 = np.load(os.path.join("projection_results", image1_name, "projected_w.npz"))['w']
#     latent_vector_2 = np.load(os.path.join("projection_results", image2_name, "projected_w.npz"))['w']

#     latent_1_tensor = torch.from_numpy(latent_vector_1).to(device)
#     latent_2_tensor = torch.from_numpy(latent_vector_2).to(device)

#     mixed_latent = latent_1_tensor.clone()
#     mixed_latent[:, styles_to_mix] = latent_2_tensor[:, styles_to_mix]

#     with torch.no_grad():
#         image = G.synthesis(mixed_latent, noise_mode='const')

#     image = (image.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy()
#     mixed_image = Image.fromarray(image[0], 'RGB')
#     return mixed_image

# def style_mixing_interface(image1, image2, mix_value):
#     if image1 is None or image2 is None:
#         return None, None
#     selected_layers = list(range(mix_value + 1))
#     mixed_img = mix_styles(image1, image2, selected_layers)

#     buffer = io.BytesIO()
#     mixed_img.save(buffer, format="PNG")
#     buffer.seek(0)
#     return mixed_img, buffer

# def send_to_backend(image_buffer, user_id):
#     if not user_id:
#         return "❌ user_id not found."

#     try:
#         files = {'file': ('generated_image.png', image_buffer, 'image/png')}
#         url = f"https://5a4d-103-40-74-78.ngrok-free.app/customisation/upload/{user_id}"

#         response = requests.post(url, files=files)

#         if response.status_code == 201:
#             return "βœ… Image uploaded and saved to database!"
#         else:
#             return f"❌ Upload failed: {response.status_code} - {response.text}"

#     except Exception as e:
#         return f"⚠️ Error: {str(e)}"

# # --- Gradio UI ---
# with gr.Blocks(title="Style Mixing for Clothing Design") as iface:

#     user_id_state = gr.State()

#     @iface.load(inputs=None, outputs=[user_id_state])
#     def on_load(request: gr.Request):
#         user_id = request.query_params.get('user_id', '')
#         return user_id

#     gr.Markdown("## Style Mixing for Clothing Design\nUpload two projected clothing images and mix their styles.")

#     with gr.Row():
#         image1_input = gr.Image(label="First Clothing Image", type="filepath")
#         image2_input = gr.Image(label="Second Clothing Image", type="filepath")

#     mix_slider = gr.Slider(label="Style Mixing Strength (Layers 0 to N)", minimum=0, maximum=9, step=1, value=5)

#     with gr.Row():
#         output_image = gr.Image(label="Mixed Clothing Design")
#         save_button = gr.Button("Download & Save to Database")

#     image_buffer = gr.State()
#     save_status = gr.Textbox(label="Save Status", interactive=False)

#     def mix_and_store(image1, image2, mix_value):
#         result_image, buffer = style_mixing_interface(image1, image2, mix_value)
#         return result_image, buffer

#     mix_slider.change(mix_and_store, inputs=[image1_input, image2_input, mix_slider], outputs=[output_image, image_buffer])
#     save_button.click(send_to_backend, inputs=[image_buffer, user_id_state], outputs=[save_status])

# iface.launch()










import gradio as gr
import torch
import numpy as np
from PIL import Image
import os
import legacy
import torch_utils
import requests
import io
import warnings
import gdown

warnings.filterwarnings("ignore")

# -------- CONFIGURATION --------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Google Drive model setup
file_id = "12_fsSQgUfOCAPQaDtq2QPCLE74qTQEwt"
output_path = "dress_model.pkl"

# Download the model if it's not present
if not os.path.exists(output_path):
    print("Downloading StyleGAN2 model from Google Drive...")
    gdown.download(f"https://drive.google.com/uc?id={file_id}", output_path, quiet=False)

# Load the model
with open(output_path, 'rb') as f:
    G = legacy.load_network_pkl(f)['G_ema'].to(device)

# Save model path for projector.py
NETWORK_PKL = output_path

# -------- ENSURE PROJECTION --------
def ensure_projection(image_path):
    image_name = os.path.splitext(os.path.basename(image_path))[0]
    proj_dir = os.path.join("projection_results", image_name)
    proj_file = os.path.join(proj_dir, "projected_w.npz")

    if not os.path.exists(proj_file):
        print(f"Projection for {image_name} not found. Running projector.py...")
        os.makedirs(proj_dir, exist_ok=True)
        subprocess.run([
            "python", "projector.py",
            f"--network={NETWORK_PKL}",
            f"--target={image_path}",
            f"--outdir={proj_dir}"
        ], check=True)
    return proj_file

# -------- STYLE MIXING --------
def mix_styles(image1_path, image2_path, styles_to_mix):
    proj_file1 = ensure_projection(image1_path)
    proj_file2 = ensure_projection(image2_path)

    latent_vector_1 = np.load(proj_file1)['w']
    latent_vector_2 = np.load(proj_file2)['w']

    latent_1_tensor = torch.from_numpy(latent_vector_1).to(device)
    latent_2_tensor = torch.from_numpy(latent_vector_2).to(device)

    mixed_latent = latent_1_tensor.clone()
    mixed_latent[:, styles_to_mix] = latent_2_tensor[:, styles_to_mix]

    with torch.no_grad():
        image = G.synthesis(mixed_latent, noise_mode='const')

    image = (image.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy()
    mixed_image = Image.fromarray(image[0], 'RGB')
    return mixed_image



# Handles style mixing + output buffer
def style_mixing_interface(image1, image2, mix_value):
    if image1 is None or image2 is None:
        return None, None
    selected_layers = list(range(mix_value + 1))
    mixed_img = mix_styles(image1, image2, selected_layers)

    buffer = io.BytesIO()
    mixed_img.save(buffer, format="PNG")
    buffer.seek(0)
    return mixed_img, buffer

# Upload to NestJS backend
def send_to_backend(image_buffer, user_id):
    if not user_id:
        return "❌ user_id not found."
    if image_buffer is None:
        return "⚠️ No image generated. Please mix styles first."

    try:
        # Convert BytesIO to raw bytes before sending
        file_bytes = image_buffer.getvalue()

        files = {'file': ('generated_image.png', file_bytes, 'image/png')}

        # Update with your actual ngrok or server URL
        url = f"  https://68be601de1e4.ngrok-free.app/customisation/upload/{user_id}"

        response = requests.post(url, files=files)

        if response.status_code == 201:
            return "βœ… Image uploaded and saved to database!"
        else:
            return f"❌ Upload failed: {response.status_code} - {response.text}"

    except Exception as e:
        return f"⚠️ Error: {str(e)}"


# Gradio interface
# with gr.Blocks(title="Style Mixing for Clothing Designs") as iface:
#     user_id_state = gr.State()

#     @iface.load(inputs=None, outputs=[user_id_state])
#     def on_load(request: gr.Request):
#         user_id = request.query_params.get('user_id', '')
#         return user_id

#     gr.Markdown("## Style Mixing for Clothing Design\nUpload two projected clothing images and mix their styles.")

#     with gr.Row():
#         image1_input = gr.Image(label="First Clothing Image", type="filepath")
#         image2_input = gr.Image(label="Second Clothing Image", type="filepath")

#     mix_slider = gr.Slider(label="Style Mixing Strength", minimum=0, maximum=9, step=1, value=5)

#     with gr.Row():
#         output_image = gr.Image(label="Mixed Clothing Design")
#         save_button = gr.Button("Download & Save to Database")

#     image_buffer = gr.State()
#     save_status = gr.Textbox(label="Save Status", interactive=False)

#     def mix_and_store(image1, image2, mix_value):
#         result_image, buffer = style_mixing_interface(image1, image2, mix_value)
#         return result_image, buffer

#     mix_button = gr.Button("Mix Styles")
#     mix_button.click(mix_and_store, inputs=[image1_input, image2_input, mix_slider], outputs=[output_image, image_buffer])
#     save_button.click(send_to_backend, inputs=[image_buffer, user_id_state], outputs=[save_status])

# iface.launch()
import gradio as gr

with gr.Blocks(title="Style Mixing for Clothing Designs") as iface:
    user_id_state = gr.State()
    image_buffer = gr.State()

    # Load user ID from URL
    @iface.load(inputs=None, outputs=[user_id_state])
    def on_load(request: gr.Request):
        user_id = request.query_params.get('user_id', '')
        return user_id

    # Header
    gr.Markdown("## 🎨 Style Mixing for Clothing Designs")
    gr.Markdown("Upload two projected clothing images and blend their styles using the slider below.")

    # Upload Inputs
    with gr.Group():
        with gr.Row():
            image1_input = gr.Image(label="πŸ‘— First Clothing Image", type="filepath",height=256, width=256)
            image2_input = gr.Image(label="πŸ‘— Second Clothing Image", type="filepath",height=256, width=256)
        mix_slider = gr.Slider(label="πŸ§ͺ Style Mixing Intensity", minimum=0, maximum=9, step=1, value=5, info="0 = Mostly Left | 9 = Mostly Right")

    # Output & Actions
    with gr.Group():
        with gr.Row():
            output_image = gr.Image(label="🧡 Mixed Clothing Design",height=256, width=256)
        with gr.Row():
            mix_button = gr.Button("✨ Mix Styles")
            save_button = gr.Button("πŸ’Ύ Save to Database")
        save_status = gr.Textbox(label="Status", interactive=False)

    # Functions
    def mix_and_store(image1, image2, mix_value):
        result_image, buffer = style_mixing_interface(image1, image2, mix_value)
        return result_image, buffer

    # Button Logic
    mix_button.click(
        fn=mix_and_store,
        inputs=[image1_input, image2_input, mix_slider],
        outputs=[output_image, image_buffer]
    )

    save_button.click(
        fn=send_to_backend,
        inputs=[image_buffer, user_id_state],
        outputs=[save_status]
    )

iface.launch()