uhdessai commited on
Commit
e91befd
·
verified ·
1 Parent(s): 55039df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -138
app.py CHANGED
@@ -3,168 +3,204 @@
3
  # import os
4
  # import random
5
  # from PIL import Image
 
 
6
 
7
- # # Paths
8
- # OUTPUT_DIR = "outputs"
9
- # MODEL_PATH = "blazer_model.pkl" # Adjusted for local Hugging Face repo structure
 
 
 
10
 
11
- # # Ensure the output directory exists
12
  # os.makedirs(OUTPUT_DIR, exist_ok=True)
 
13
 
14
- # # Function to generate images using StyleGAN3
15
  # def generate_images():
16
- # command = f"python stylegan3/gen_images.py --outdir={OUTPUT_DIR} --trunc=1 --seeds='3-5,7,9,12-14,16-26,29,31,32,34,40,41' --network={MODEL_PATH}"
 
 
 
 
 
 
 
17
  # try:
18
- # subprocess.run(command, shell=True, check=True)
19
  # except subprocess.CalledProcessError as e:
20
- # return f"Error generating images: {e}"
21
 
22
- # # Function to select 5 random images
23
  # def get_random_images():
24
  # image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
25
  # if len(image_files) < 10:
26
  # generate_images()
27
  # image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
28
  # random_images = random.sample(image_files, min(10, len(image_files)))
29
- # return [Image.open(os.path.join(OUTPUT_DIR, img)) for img in random_images]
 
30
 
31
- # # Gradio function
32
- # def generate_and_display():
33
- # generate_images()
34
- # return get_random_images()
35
 
36
- # # UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  # with gr.Blocks() as demo:
38
  # gr.Markdown("# 🎨 AI-Generated Clothing Designs - Blazers")
 
39
  # generate_button = gr.Button("Generate New Designs")
40
- # output_gallery = gr.Gallery(label="Generated Designs", columns=5, rows=2)
41
- # generate_button.click(fn=generate_and_display, outputs=output_gallery)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  # if __name__ == "__main__":
44
  # demo.launch()
45
 
46
-
47
-
48
-
49
- import gradio as gr
50
- import subprocess
51
- import os
52
- import random
53
  from PIL import Image
54
- import shutil
55
- import requests
56
-
57
- # === Setup Paths ===
58
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
59
- GEN_SCRIPT = os.path.join(BASE_DIR, "stylegan3", "gen_images.py")
60
- OUTPUT_DIR = os.path.join(BASE_DIR, "outputs")
61
- MODEL_PATH = os.path.join(BASE_DIR, "blazer_model.pkl")
62
- SAVE_DIR = os.path.join(BASE_DIR, "saved_images")
63
-
64
- os.makedirs(OUTPUT_DIR, exist_ok=True)
65
- os.makedirs(SAVE_DIR, exist_ok=True)
66
-
67
- # === Image Generation Function ===
68
- def generate_images():
69
- command = [
70
- "python",
71
- GEN_SCRIPT,
72
- f"--outdir={OUTPUT_DIR}",
73
- "--trunc=1",
74
- "--seeds=3-5,7,9,12-14,16-26,29,31,32,34,40,41",
75
- f"--network={MODEL_PATH}"
76
- ]
77
- try:
78
- subprocess.run(command, check=True, capture_output=True, text=True)
79
- except subprocess.CalledProcessError as e:
80
- return f"Error generating images:\n{e.stderr}"
81
-
82
- # === Select Random Images from Output Folder ===
83
- def get_random_images():
84
- image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
85
- if len(image_files) < 10:
86
- generate_images()
87
- image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
88
- random_images = random.sample(image_files, min(10, len(image_files)))
89
- image_paths = [os.path.join(OUTPUT_DIR, img) for img in random_images]
90
- return image_paths
91
-
92
- # === Send Image to Backend ===
93
- def send_to_backend(img_path, user_id):
94
- if not user_id:
95
- return "❌ user_id not found in URL."
96
-
97
- if not img_path or not os.path.exists(img_path):
98
- return "⚠️ No image selected or image not found."
99
-
100
- try:
101
- with open(img_path, 'rb') as f:
102
- files = {'file': ('generated_image.png', f, 'image/png')}
103
-
104
- # Your backend endpoint here
105
- url = f" https://7da2-2409-4042-6e81-1806-de6-b8e5-836c-6b95.ngrok-free.app/images/upload/{user_id}"
106
- response = requests.post(url, files=files)
107
-
108
- if response.status_code == 201:
109
- return "✅ Image uploaded and saved to database!"
110
- else:
111
- return f"❌ Upload failed: {response.status_code} - {response.text}"
112
-
113
- except Exception as e:
114
- return f"⚠️ Error: {str(e)}"
115
-
116
- # === Gradio Interface ===
117
- with gr.Blocks() as demo:
118
- gr.Markdown("# 🎨 AI-Generated Clothing Designs - Blazers")
119
-
120
- generate_button = gr.Button("Generate New Designs")
121
- user_id_state = gr.State()
122
-
123
- @demo.load(inputs=None, outputs=[user_id_state])
124
- def get_user_id(request: gr.Request):
125
- return request.query_params.get("user_id", "")
126
-
127
- image_components = []
128
- file_paths = []
129
- save_buttons = []
130
- outputs = []
131
-
132
- # Use 3 columns layout
133
- for row_idx in range(4): # 4 rows (to cover 10 images)
134
- with gr.Row():
135
- for col_idx in range(3): # 3 columns
136
- i = row_idx * 3 + col_idx
137
- if i >= 10:
138
- break
139
- with gr.Column():
140
- img = gr.Image(width=180, height=180, label=f"Design {i+1}")
141
- image_components.append(img)
142
-
143
- file_path = gr.Textbox(visible=False)
144
- file_paths.append(file_path)
145
-
146
- save_btn = gr.Button("💾 Save to DB")
147
- save_buttons.append(save_btn)
148
-
149
- output = gr.Textbox(label="Status", interactive=False)
150
- outputs.append(output)
151
-
152
- save_btn.click(
153
- fn=send_to_backend,
154
- inputs=[file_path, user_id_state],
155
- outputs=output
156
- )
157
-
158
- # Generate button logicg
159
- def generate_and_display_images():
160
- image_paths = get_random_images()
161
- return image_paths + image_paths # One for display, one for hidden path tracking
162
-
163
- generate_button.click(
164
- fn=generate_and_display_images,
165
- outputs=image_components + file_paths
166
  )
167
 
168
- if __name__ == "__main__":
169
- demo.launch()
170
 
 
 
3
  # import os
4
  # import random
5
  # from PIL import Image
6
+ # import shutil
7
+ # import requests
8
 
9
+ # # === Setup Paths ===
10
+ # BASE_DIR = os.path.dirname(os.path.abspath(__file__))
11
+ # GEN_SCRIPT = os.path.join(BASE_DIR, "stylegan3", "gen_images.py")
12
+ # OUTPUT_DIR = os.path.join(BASE_DIR, "outputs")
13
+ # MODEL_PATH = os.path.join(BASE_DIR, "blazer_model.pkl")
14
+ # SAVE_DIR = os.path.join(BASE_DIR, "saved_images")
15
 
 
16
  # os.makedirs(OUTPUT_DIR, exist_ok=True)
17
+ # os.makedirs(SAVE_DIR, exist_ok=True)
18
 
19
+ # # === Image Generation Function ===
20
  # def generate_images():
21
+ # command = [
22
+ # "python",
23
+ # GEN_SCRIPT,
24
+ # f"--outdir={OUTPUT_DIR}",
25
+ # "--trunc=1",
26
+ # "--seeds=3-5,7,9,12-14,16-26,29,31,32,34,40,41",
27
+ # f"--network={MODEL_PATH}"
28
+ # ]
29
  # try:
30
+ # subprocess.run(command, check=True, capture_output=True, text=True)
31
  # except subprocess.CalledProcessError as e:
32
+ # return f"Error generating images:\n{e.stderr}"
33
 
34
+ # # === Select Random Images from Output Folder ===
35
  # def get_random_images():
36
  # image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
37
  # if len(image_files) < 10:
38
  # generate_images()
39
  # image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
40
  # random_images = random.sample(image_files, min(10, len(image_files)))
41
+ # image_paths = [os.path.join(OUTPUT_DIR, img) for img in random_images]
42
+ # return image_paths
43
 
44
+ # # === Send Image to Backend ===
45
+ # def send_to_backend(img_path, user_id):
46
+ # if not user_id:
47
+ # return "❌ user_id not found in URL."
48
 
49
+ # if not img_path or not os.path.exists(img_path):
50
+ # return "⚠️ No image selected or image not found."
51
+
52
+ # try:
53
+ # with open(img_path, 'rb') as f:
54
+ # files = {'file': ('generated_image.png', f, 'image/png')}
55
+
56
+ # # Your backend endpoint here
57
+ # url = f" https://7da2-2409-4042-6e81-1806-de6-b8e5-836c-6b95.ngrok-free.app/images/upload/{user_id}"
58
+ # response = requests.post(url, files=files)
59
+
60
+ # if response.status_code == 201:
61
+ # return "✅ Image uploaded and saved to database!"
62
+ # else:
63
+ # return f"❌ Upload failed: {response.status_code} - {response.text}"
64
+
65
+ # except Exception as e:
66
+ # return f"⚠️ Error: {str(e)}"
67
+
68
+ # # === Gradio Interface ===
69
  # with gr.Blocks() as demo:
70
  # gr.Markdown("# 🎨 AI-Generated Clothing Designs - Blazers")
71
+
72
  # generate_button = gr.Button("Generate New Designs")
73
+ # user_id_state = gr.State()
74
+
75
+ # @demo.load(inputs=None, outputs=[user_id_state])
76
+ # def get_user_id(request: gr.Request):
77
+ # return request.query_params.get("user_id", "")
78
+
79
+ # image_components = []
80
+ # file_paths = []
81
+ # save_buttons = []
82
+ # outputs = []
83
+
84
+ # # Use 3 columns layout
85
+ # for row_idx in range(4): # 4 rows (to cover 10 images)
86
+ # with gr.Row():
87
+ # for col_idx in range(3): # 3 columns
88
+ # i = row_idx * 3 + col_idx
89
+ # if i >= 10:
90
+ # break
91
+ # with gr.Column():
92
+ # img = gr.Image(width=180, height=180, label=f"Design {i+1}")
93
+ # image_components.append(img)
94
+
95
+ # file_path = gr.Textbox(visible=False)
96
+ # file_paths.append(file_path)
97
+
98
+ # save_btn = gr.Button("💾 Save to DB")
99
+ # save_buttons.append(save_btn)
100
+
101
+ # output = gr.Textbox(label="Status", interactive=False)
102
+ # outputs.append(output)
103
+
104
+ # save_btn.click(
105
+ # fn=send_to_backend,
106
+ # inputs=[file_path, user_id_state],
107
+ # outputs=output
108
+ # )
109
+
110
+ # # Generate button logicg
111
+ # def generate_and_display_images():
112
+ # image_paths = get_random_images()
113
+ # return image_paths + image_paths # One for display, one for hidden path tracking
114
+
115
+ # generate_button.click(
116
+ # fn=generate_and_display_images,
117
+ # outputs=image_components + file_paths
118
+ # )
119
 
120
  # if __name__ == "__main__":
121
  # demo.launch()
122
 
123
+ import torch
124
+ from transformers import CLIPModel, CLIPProcessor
 
 
 
 
 
125
  from PIL import Image
126
+ import numpy as np
127
+ import pickle
128
+ import gradio as gr
129
+
130
+ # Force CPU usage for optimization
131
+ device = torch.device("cpu")
132
+
133
+ # Load your GAN model
134
+ with open("/content/drive/MyDrive/clothGAN/blazer_model.pkl", "rb") as f:
135
+ G = pickle.load(f)['G_ema'].eval().cpu() # Ensure model is in eval mode and on CPU
136
+
137
+ # Load CLIP model and processor
138
+ clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval().cpu()
139
+ clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
140
+
141
+ # Generate images
142
+ def generate_images(G, num_images=10): # Reduce for CPU performance
143
+ z = torch.randn(num_images, G.z_dim)
144
+ c = None
145
+ with torch.no_grad():
146
+ images = G(z, c)
147
+ images = (images.clamp(-1, 1) + 1) * (255 / 2)
148
+ images = images.permute(0, 2, 3, 1).numpy().astype(np.uint8)
149
+ return z, images
150
+
151
+ # Rank images using CLIP
152
+ def rank_by_clip(images, prompt, top_k=3): # Reduce top_k for speed
153
+ images_pil = [Image.fromarray(img) for img in images]
154
+ inputs = clip_processor(text=[prompt], images=images_pil, return_tensors="pt", padding=True)
155
+
156
+ with torch.no_grad():
157
+ image_features = clip_model.get_image_features(pixel_values=inputs["pixel_values"])
158
+ text_features = clip_model.get_text_features(input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"])
159
+
160
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
161
+ text_features = text_features / text_features.norm(dim=-1, keepdim=True)
162
+
163
+ similarity = (image_features @ text_features.T).squeeze()
164
+
165
+ top_indices = similarity.argsort(descending=True)[:top_k]
166
+ best_images = [images_pil[i] for i in top_indices]
167
+ return best_images
168
+
169
+ # Gradio interface function
170
+ def generate_top_dresses(prompt):
171
+ _, images = generate_images(G, num_images=20)
172
+ top_images = rank_by_clip(images, prompt, top_k=2)
173
+ return top_images
174
+
175
+ # Launch Gradio
176
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
177
+ gr.Markdown("""
178
+ # 👔 AI Blazer Generator
179
+ _Type in your dream outfit, and let the AI bring your fashion vision to life!_
180
+ Just describe your ideal blazer, and see how AI transforms your words into fashion.
181
+ """)
182
+
183
+ with gr.Row():
184
+ input_box = gr.Textbox(
185
+ label="Describe your blazer",
186
+ placeholder="e.g., 'Beige blazer with gold buttons and slim fit'",
187
+ lines=2
188
+ )
189
+
190
+ with gr.Row():
191
+ submit_button = gr.Button("Generate Designs")
192
+
193
+ output_gallery = gr.Gallery(label="Generated Designs", show_label=True, columns=2, height="auto")
194
+
195
+
196
+ examples = gr.Examples(
197
+ examples = [
198
+ ["Black velvet blazer"],
199
+ ["Pink blazer with buttons"]
200
+ ],
201
+ inputs=[input_box]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  )
203
 
204
+ submit_button.click(fn=generate_top_dresses, inputs=input_box, outputs=output_gallery)
 
205
 
206
+ demo.launch()