Spaces:
Sleeping
Sleeping
File size: 10,487 Bytes
8e7d931 e91befd 8e7d931 e91befd 8e7d931 e91befd 8e7d931 a1e7596 8e7d931 e91befd 8e7d931 e91befd 8e7d931 e91befd 8e7d931 e91befd 8e7d931 e91befd e9e1ddd 8e7d931 e55d57d f585f99 8e7d931 f585f99 e91befd f585f99 e91befd f585f99 e91befd f585f99 e91befd f585f99 e91befd 8e7d931 e91befd 8e7d931 e91befd 32db493 e91befd e55d57d 8e7d931 e91befd 934e4be e91befd 0f3b4de e91befd 13824b6 e91befd 66cfcee df701ba 66cfcee df701ba 66cfcee df701ba 66cfcee df701ba e03e443 df701ba f585f99 e91befd 47a7b61 e91befd e617eff e91befd 0f3b4de e91befd e55d57d 5b83a90 e91befd 5b83a90 e91befd 8e7d931 32db493 b62a6a4 32db493 e55d57d b62a6a4 e55d57d 2e118f3 8e7d931 b62a6a4 e91befd |
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 |
# import gradio as gr
# import subprocess
# import os
# import random
# from PIL import Image
# import shutil
# import requests
# # === Setup Paths ===
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# GEN_SCRIPT = os.path.join(BASE_DIR, "stylegan3", "gen_images.py")
# OUTPUT_DIR = os.path.join(BASE_DIR, "outputs")
# MODEL_PATH = os.path.join(BASE_DIR, "blazer_model.pkl")
# SAVE_DIR = os.path.join(BASE_DIR, "saved_images")
# os.makedirs(OUTPUT_DIR, exist_ok=True)
# os.makedirs(SAVE_DIR, exist_ok=True)
# # === Image Generation Function ===h
# def generate_images():
# command = [
# "python",
# GEN_SCRIPT,
# f"--outdir={OUTPUT_DIR}",
# "--trunc=1",
# "--seeds=3-5,7,9,12-14,16-26,29,31,32,34,40,41",
# f"--network={MODEL_PATH}"
# ]
# try:
# subprocess.run(command, check=True, capture_output=True, text=True)
# except subprocess.CalledProcessError as e:
# return f"Error generating images:\n{e.stderr}"
# # === Select Random Images from Output Folder ===
# def get_random_images():
# image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
# if len(image_files) < 10:
# generate_images()
# image_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".png")]
# random_images = random.sample(image_files, min(10, len(image_files)))
# image_paths = [os.path.join(OUTPUT_DIR, img) for img in random_images]
# return image_pathsgg
# === Send Image to Backend ===
# def send_to_backend(img_path, user_id):
# if not user_id:
# return "β user_id not found in URL."
# if not img_path or not os.path.exists(img_path):
# return "β οΈ No image selected or image not found."
# try:
# with open(img_path, 'rb') as f:
# files = {'file': ('generated_image.png', f, 'image/png')}
# # Your backend endpoint here
# url = f"https://e335-103-40-74-83.ngrok-free.app/images/upload/{user_id}"
# response = requests.post(url, files=files)
# if response.status_code == 201:
# return "β
Image uploaded and saved to database!"
# else:
# console.log({response.text})
# return f"β Upload failed: {response.status_code} - {response.text}"
# except Exception as e:
# return f"β οΈ Error: {str(e)}"
# # === Gradio Interface ===
# with gr.Blocks() as demo:
# gr.Markdown("# π¨ AI-Generated Clothing Designs - Blazers")
# generate_button = gr.Button("Generate New Designs")
# user_id_state = gr.State()
# @demo.load(inputs=None, outputs=[user_id_state])
# def get_user_id(request: gr.Request):
# return request.query_params.get("user_id", "")
# image_components = []
# file_paths = []
# save_buttons = []
# outputs = []
# # Use 3 columns layout
# for row_idx in range(4): # 4 rows (to cover 10 images)
# with gr.Row():
# for col_idx in range(3): # 3 columns
# i = row_idx * 3 + col_idx
# if i >= 10:
# break
# with gr.Column():
# img = gr.Image(width=180, height=180, label=f"Design {i+1}")
# image_components.append(img)
# file_path = gr.Textbox(visible=False)
# file_paths.append(file_path)
# save_btn = gr.Button("πΎ Save to DB")
# save_buttons.append(save_btn)
# output = gr.Textbox(label="Status", interactive=False)
# outputs.append(output)
# save_btn.click(
# fn=send_to_backend,
# inputs=[file_path, user_id_state],
# outputs=output
# )
# generate_button.click(
# fn=generate_and_display_images,
# outputs=image_components + file_paths
# )
# if __name__ == "__main__":
# demo.launch()
import torch
from transformers import CLIPModel, CLIPProcessor
from PIL import Image
import numpy as np
import pickle
import gradio as gr
import tempfile
# Force CPU usage for optimization
device = torch.device("cpu")
# Load your GAN model
with open("blazer_model.pkl", "rb") as f:
G = pickle.load(f)['G_ema'].eval().cpu() # Ensure model is in eval mode and on CPU
# Load CLIP model and processor
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval().cpu()
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
# def send_to_backend(img_path, user_id):
# if not user_id:
# return "β user_id not found in URL."
# if not img_path or not os.path.exists(img_path):
# return "β οΈ No image selected or image not found."
# try:
# with open(img_path, 'rb') as f:
# files = {'file': ('generated_image.png', f, 'image/png')}
# # Your backend endpoint here
# url = f"https://e335-103-40-74-83.ngrok-free.app/images/upload/{user_id}"
# response = requests.post(url, files=files)
# if response.status_code == 201:
# return "β
Image uploaded and saved to database!"
# else:
# console.log({response.text})
# return f"β Upload failed: {response.status_code} - {response.text}"
# except Exception as e:
# return f"β οΈ Error: {str(e)}"
import os
import requests # Make sure you import this!
def send_to_backend(img_path, user_id):
print(f"π‘ [DEBUG] Sending image to backend | img_path={img_path}, user_id={user_id}")
if not user_id:
print("β [DEBUG] Missing user_id in URL.")
return "β user_id not found in URL."
if not img_path or not os.path.exists(img_path):
print("β οΈ [DEBUG] Image path invalid or does not exist.")
return "β οΈ No image selected or image not found."
try:
with open(img_path, 'rb') as f:
files = {'file': ('generated_image.png', f, 'image/png')}
url = f" https://68be601de1e4.ngrok-free.app/images/upload/{user_id}"
print(f"π [DEBUG] Sending POST to {url}")
response = requests.post(url, files=files)
print(f"π© [DEBUG] Response: {response.status_code} - {response.text}")
if response.status_code == 201 or response.status_code == 200:
return "β
Image uploaded and saved to database!"
else:
return f"β Upload failed: {response.status_code} - {response.text}"
except Exception as e:
print(f"β οΈ [ERROR] Exception during upload: {str(e)}")
return f"β οΈ Error: {str(e)}"
# Generate images
def generate_images(G, num_images=10): # Reduce for CPU performance
z = torch.randn(num_images, G.z_dim)
c = None
with torch.no_grad():
images = G(z, c)
images = (images.clamp(-1, 1) + 1) * (255 / 2)
images = images.permute(0, 2, 3, 1).numpy().astype(np.uint8)
return z, images
# Rank images using CLIP
def rank_by_clip(images, prompt, top_k=3): # Reduce top_k for speedh
images_pil = [Image.fromarray(img) for img in images]
inputs = clip_processor(text=[prompt], images=images_pil, return_tensors="pt", padding=True)
with torch.no_grad():
image_features = clip_model.get_image_features(pixel_values=inputs["pixel_values"])
text_features = clip_model.get_text_features(input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"])
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
similarity = (image_features @ text_features.T).squeeze()
top_indices = similarity.argsort(descending=True)[:top_k]
best_images = [images_pil[i] for i in top_indices]
return best_images
# Gradio interface function
def generate_top_dresses(prompt):
_, images = generate_images(G, num_images=30)
top_images = rank_by_clip(images, prompt, top_k=2)
file_paths = []
for i, img in enumerate(top_images):
temp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
img.save(temp_path)
file_paths.append(temp_path)
return top_images, file_paths
# Launch Gradio
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
gr.Markdown("""
# π AI Blazer Generator
_Type in your dream outfit, and let the AI bring your fashion vision to life!_
Just describe your ideal blazer, and see how AI transforms your words into fashion.
""")
with gr.Row():
input_box = gr.Textbox(
label="Describe your blazer",
placeholder="e.g., 'Beige blazer with gold buttons and slim fit'",
lines=2
)
with gr.Row():
submit_button = gr.Button("Generate Designs")
user_id_state = gr.State()
@demo.load(inputs=None, outputs=[user_id_state])
def get_user_id(request: gr.Request):
return request.query_params.get("user_id", "")
image_components = []
file_paths = []
save_buttons = []
outputs = []
with gr.Row():
for i in range(2): # Only 2 images
with gr.Column():
img = gr.Image(width=180, height=180, label=f"Design {i+1}")
image_components.append(img)
file_path = gr.Textbox(visible=False)
file_paths.append(file_path)
save_btn = gr.Button("πΎ Save to DB")
save_buttons.append(save_btn)
output = gr.Textbox(label="Status", interactive=False)
outputs.append(output)
save_btn.click(
fn=send_to_backend,
inputs=[file_path, user_id_state],
outputs=output
)
examples = gr.Examples(
examples = [
["Black velvet blazer"],
["Pink blazer with buttons"]
],
inputs=[input_box]
)
# Generate button logicg
def generate_and_display_images(prompt):
images, paths = generate_top_dresses(prompt)
return images + paths
submit_button.click(
fn=generate_and_display_images,
inputs=[input_box],
outputs=image_components + file_paths
)
demo.launch()
|