babatdaa commited on
Commit
b976206
·
verified ·
1 Parent(s): 2dcfe74

Write a detailed Python code using Stable Diffusion (via diffusers library) and a predictive ML model (e.g., TensorFlow for regression) to generate custom images for e-commerce, such as product mockups personalized to predicted user trends from sales data. The predictive part should process input data (e.g., CSV of customer demographics) to forecast popular styles/colors, then condition the image generation accordingly. Include steps for model setup, training on datasets like LAION, and API endpoints for automation. Tailor for freelancers building tools for businesses needing visual content creation, considering the 220% YoY demand surge.

Browse files
Files changed (1) hide show
  1. ecommerce-image-generator.py +465 -0
ecommerce-image-generator.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```python
2
+ #!/usr/bin/env python3
3
+ """
4
+ AI Forge E-commerce Image Generator
5
+ Stable Diffusion + Predictive ML for personalized product mockups
6
+ Optimized for 220% YoY demand growth in visual content creation
7
+ """
8
+
9
+ import os
10
+ import torch
11
+ import pandas as pd
12
+ import numpy as np
13
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
14
+ import tensorflow as tf
15
+ from tensorflow import keras
16
+ from tensorflow.keras import layers
17
+ import matplotlib.pyplot as plt
18
+ from PIL import Image
19
+ import io
20
+ import base64
21
+ import warnings
22
+ warnings.filterwarnings('ignore')
23
+
24
+ # Configuration
25
+ class Config:
26
+ """Configuration parameters for the image generation system"""
27
+ STABLE_DIFFUSION_MODEL = "runwayml/stable-diffusion-v1-5"
28
+ IMAGE_SIZE = (512, 512)
29
+ MAX_LENGTH = 77
30
+ BATCH_SIZE = 4
31
+ EPOCHS = 50
32
+ LEARNING_RATE = 1e-4
33
+ PREDICTION_MODEL_PATH = "./models/style_predictor.h5"
34
+ TRAINING_DATA_PATH = "./data/ecommerce_sales.csv"
35
+ OUTPUT_DIR = "./generated_images"
36
+
37
+ # Style categories for prediction
38
+ STYLE_CATEGORIES = ['minimalist', 'vintage', 'modern', 'luxury', 'tech', 'sporty']
39
+ COLOR_CATEGORIES = ['blue', 'red', 'green', 'black', 'white', 'pastel', 'neon']
40
+ PRODUCT_TYPES = ['clothing', 'electronics', 'home_decor', 'beauty', 'accessories']
41
+
42
+ class StylePredictor:
43
+ """TensorFlow model for predicting trending styles and colors"""
44
+
45
+ def __init__(self, input_dim):
46
+ self.input_dim = input_dim
47
+ self.model = None
48
+
49
+ def build_model(self):
50
+ """Build the style prediction model"""
51
+ model = keras.Sequential([
52
+ layers.Dense(256, activation='relu', input_shape=(input_dim,)),
53
+ layers.Dropout(0.3),
54
+ layers.Dense(128, activation='relu'),
55
+ layers.Dropout(0.2),
56
+ layers.Dense(64, activation='relu'),
57
+ layers.Dense(len(Config.STYLE_CATEGORIES) + len(Config.COLOR_CATEGORIES)),
58
+ layers.Activation('sigmoid')
59
+ ])
60
+
61
+ model.compile(
62
+ optimizer=keras.optimizers.Adam(learning_rate=Config.LEARNING_RATE),
63
+ loss='binary_crossentropy',
64
+ metrics=['accuracy']
65
+ )
66
+
67
+ self.model = model
68
+ return model
69
+
70
+ def train(self, X_train, y_train, X_val=None, y_val=None):
71
+ """Train the style prediction model"""
72
+ callbacks = [
73
+ keras.callbacks.EarlyStopping(patience=10, restore_best_weights=True),
74
+ keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=5),
75
+ keras.callbacks.ModelCheckpoint(
76
+ Config.PREDICTION_MODEL_PATH,
77
+ save_best_only=True,
78
+ monitor='val_loss' if X_val is not None else 'loss'
79
+ )
80
+ ]
81
+
82
+ history = self.model.fit(
83
+ X_train, y_train,
84
+ batch_size=Config.BATCH_SIZE,
85
+ epochs=Config.EPOCHS,
86
+ validation_data=(X_val, y_val) if X_val is not None else None,
87
+ callbacks=callbacks,
88
+ verbose=1
89
+ )
90
+
91
+ return history
92
+
93
+ def predict_trends(self, customer_data):
94
+ """Predict trending styles and colors for customer segment"""
95
+ predictions = self.model.predict(customer_data)
96
+
97
+ # Split predictions into styles and colors
98
+ style_predictions = predictions[:, :len(Config.STYLE_CATEGORIES)]
99
+ color_predictions = predictions[:, len(Config.STYLE_CATEGORIES):]
100
+
101
+ return style_predictions, color_predictions
102
+
103
+ class EcommerceDataProcessor:
104
+ """Process e-commerce sales data for trend prediction"""
105
+
106
+ def __init__(self):
107
+ self.feature_columns = []
108
+
109
+ def load_and_preprocess_data(self, file_path):
110
+ """Load and preprocess e-commerce sales data"""
111
+ try:
112
+ df = pd.read_csv(file_path)
113
+ print(f"Loaded dataset with {len(df)} rows")
114
+ return df
115
+ except Exception as e:
116
+ print(f"Error loading data: {e}")
117
+ return None
118
+
119
+ def extract_features(self, df):
120
+ """Extract features from e-commerce data"""
121
+ features = []
122
+
123
+ # Demographic features
124
+ demographic_features = ['age', 'income_level', 'location_urban', 'gender_encoded']
125
+
126
+ # Time-based features
127
+ df['purchase_month'] = pd.to_datetime(df['purchase_date']).dt.month
128
+ features.append(pd.get_dummies(df['purchase_month'], prefix='month'))
129
+
130
+ # Product features
131
+ product_features = ['price', 'category_encoded', 'brand_popularity']
132
+
133
+ # Combine all features
134
+ for feature in demographic_features + ['purchase_month', 'price', 'category_encoded', 'brand_popularity']:
135
+ if feature in df.columns:
136
+ features.append(df[[feature]]))
137
+
138
+ # One-hot encode categorical variables
139
+ categorical_cols = ['region', 'device_type', 'marketing_channel']
140
+ for col in categorical_cols:
141
+ if col in df.columns:
142
+ dummies = pd.get_dummies(df[col], prefix=col)
143
+ features.append(dummies)
144
+
145
+ X = pd.concat(features, axis=1)
146
+ self.feature_columns = X.columns.tolist()
147
+
148
+ return X
149
+
150
+ def prepare_training_labels(self, df):
151
+ """Prepare training labels for style and color trends"""
152
+ # Create binary labels for styles and colors based on sales performance
153
+ labels = []
154
+
155
+ for _, row in df.iterrows():
156
+ # Style preferences (based on product attributes)
157
+ style_vector = [0] * len(Config.STYLE_CATEGORIES)
158
+ color_vector = [0] * len(Config.COLOR_CATEGORIES)
159
+
160
+ # For each product, determine dominant style and color
161
+ if row['sales_rank'] <= 100: # Top selling products
162
+ # Analyze product description for style keywords
163
+ description = str(row.get('product_description', '')).lower()
164
+
165
+ for i, style in enumerate(Config.STYLE_CATEGORIES):
166
+ if style in description:
167
+ style_vector[i] = 1
168
+
169
+ # Color analysis from product data
170
+ color_data = str(row.get('color_data', '')).lower()
171
+ for j, color in enumerate(Config.COLOR_CATEGORIES):
172
+ if color in description or color in str(row.get('primary_color', '')).lower():
173
+ color_vector[j] = 1
174
+
175
+ labels.append(style_vector + color_vector)
176
+
177
+ return np.array(labels)
178
+
179
+ class StableDiffusionGenerator:
180
+ """Stable Diffusion image generator for e-commerce mockups"""
181
+
182
+ def __init__(self):
183
+ self.pipeline = None
184
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
185
+ print(f"Using device: {self.device}")
186
+
187
+ def load_model(self):
188
+ """Load Stable Diffusion model"""
189
+ try:
190
+ self.pipeline = StableDiffusionPipeline.from_pretrained(
191
+ Config.STABLE_DIFFUSION_MODEL,
192
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
193
+ )
194
+ self.pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
195
+ self.pipeline.scheduler.config
196
+ )
197
+ self.pipeline = self.pipeline.to(self.device)
198
+ print("Stable Diffusion model loaded successfully")
199
+ except Exception as e:
200
+ print(f"Error loading model: {e}")
201
+
202
+ def generate_product_mockup(self, prompt, style_weights=None, color_weights=None):
203
+ """Generate product mockup with style and color conditioning"""
204
+
205
+ # Enhance prompt based on predicted trends
206
+ enhanced_prompt = self._enhance_prompt(prompt, style_weights, color_weights)
207
+
208
+ # Generate image
209
+ with torch.autocast(self.device.type):
210
+ image = self.pipeline(
211
+ prompt,
212
+ height=Config.IMAGE_SIZE[0],
213
+ width=Config.IMAGE_SIZE[1],
214
+ num_inference_steps=25,
215
+ guidance_scale=7.5
216
+ ).images[0]
217
+
218
+ return image
219
+
220
+ def _enhance_prompt(self, base_prompt, style_weights, color_weights):
221
+ """Enhance prompt with style and color conditioning"""
222
+
223
+ if style_weights is not None:
224
+ # Get top predicted styles
225
+ top_style_indices = np.argsort(style_weights)[-2:] # Top 2 styles
226
+ top_colors_indices = np.argsort(color_weights)[-2:]
227
+
228
+ # Add style descriptors
229
+ style_descriptors = []
230
+ for idx in top_style_indices:
231
+ style_descriptors.append(Config.STYLE_CATEGORIES[idx])
232
+
233
+ # Add color descriptors
234
+ color_descriptors = []
235
+ for idx in top_colors_indices:
236
+ color_descriptors.append(Config.COLOR_CATEGORIES[idx])
237
+
238
+ enhanced_prompt = f"{base_prompt}, {', '.join(style_descriptors)} style, colors: {', '.join(color_descriptors)}"
239
+
240
+ return enhanced_prompt
241
+
242
+ def generate_batch_mockups(self, prompts, style_predictions, color_predictions):
243
+ """Generate multiple product mockups in batch"""
244
+ images = []
245
+
246
+ for i, prompt in enumerate(prompts):
247
+ style_weights = style_predictions[i] if i < len(style_predictions) else None
248
+ color_weights = color_predictions[i] if i < len(color_predictions) else None
249
+
250
+ image = self.generate_product_mockup(prompt, style_weights, color_weights)
251
+ images.append(image)
252
+
253
+ return images
254
+
255
+ class EcommerceImageAPI:
256
+ """FastAPI integration for the e-commerce image generation system"""
257
+
258
+ def __init__(self):
259
+ self.data_processor = EcommerceDataProcessor()
260
+ self.style_predictor = None
261
+ self.image_generator = StableDiffusionGenerator()
262
+
263
+ def initialize_system(self):
264
+ """Initialize the complete system"""
265
+ print("Initializing E-commerce Image Generation System...")
266
+
267
+ # Load data
268
+ df = self.data_processor.load_and_preprocess_data(Config.TRAINING_DATA_PATH)
269
+
270
+ if df is not None:
271
+ # Prepare features and labels
272
+ X = self.data_processor.extract_features(df)
273
+ y = self.data_processor.prepare_training_labels(df)
274
+
275
+ # Initialize and train style predictor
276
+ self.style_predictor = StylePredictor(X.shape[1])
277
+ self.style_predictor.build_model()
278
+
279
+ # Split data
280
+ from sklearn.model_selection import train_test_split
281
+ X_train, X_test, y_train, y_test = train_test_split(
282
+ X, y, test_size=0.2, random_state=42
283
+ )
284
+
285
+ # Train model
286
+ print("Training style prediction model...")
287
+ history = self.style_predictor.train(X_train, y_train, X_test, y_test)
288
+
289
+ # Evaluate model
290
+ test_loss, test_accuracy = self.style_predictor.model.evaluate(X_test, y_test)
291
+ print(f"Model trained - Test Accuracy: {test_accuracy:.4f}")
292
+
293
+ # Load image generator
294
+ self.image_generator.load_model()
295
+
296
+ print("System initialized successfully")
297
+
298
+ def predict_and_generate(self, customer_segment_data, base_prompts):
299
+ """Complete workflow: predict trends and generate images"""
300
+
301
+ # Predict styles and colors
302
+ style_predictions, color_predictions = self.style_predictor.predict_trends(customer_segment_data)
303
+
304
+ # Generate images
305
+ images = self.image_generator.generate_batch_mockups(
306
+ base_prompts, style_predictions, color_predictions
307
+ )
308
+
309
+ return images, style_predictions, color_predictions
310
+
311
+ # FastAPI Integration
312
+ from fastapi import FastAPI, HTTPException
313
+ from fastapi.middleware.cors import CORSMiddleware
314
+ from pydantic import BaseModel
315
+ from typing import List, Optional
316
+ import uvicorn
317
+
318
+ app = FastAPI(title="AI Forge E-commerce Image Generator")
319
+
320
+ # CORS middleware
321
+ app.add_middleware(
322
+ CORSMiddleware,
323
+ allow_origins=["*"],
324
+ allow_credentials=True,
325
+ allow_methods=["*"],
326
+ allow_headers=["*"]
327
+ )
328
+
329
+ class GenerationRequest(BaseModel):
330
+ customer_data: List[dict]
331
+ base_prompts: List[str]
332
+ num_images: int = 1
333
+
334
+ class GenerationResponse(BaseModel):
335
+ success: bool
336
+ message: str
337
+ generated_images: Optional[List[str]] = None
338
+ predicted_styles: Optional[List[str]] = None
339
+ predicted_colors: Optional[List[str]] = None
340
+
341
+ # Initialize system
342
+ ecommerce_system = EcommerceImageAPI()
343
+
344
+ @app.on_event("startup")
345
+ async def startup_event():
346
+ """Initialize system on startup"""
347
+ ecommerce_system.initialize_system()
348
+
349
+ @app.get("/")
350
+ async def root():
351
+ return {"message": "AI Forge E-commerce Image Generator API"}
352
+
353
+ @app.post("/api/generate-mockups", response_model=GenerationResponse)
354
+ async def generate_mockups(request: GenerationRequest):
355
+ """Generate product mockups based on predicted trends"""
356
+ try:
357
+ # Convert customer data to DataFrame
358
+ customer_df = pd.DataFrame(request.customer_data)
359
+
360
+ # Process customer data
361
+ X_customer = ecommerce_system.data_processor.extract_features(customer_df)
362
+
363
+ # Generate images
364
+ images, style_preds, color_preds = ecommerce_system.predict_and_generate(
365
+ X_customer,
366
+ request.base_prompts
367
+ )
368
+
369
+ # Convert images to base64 for API response
370
+ base64_images = []
371
+ for image in images:
372
+ buffered = io.BytesIO()
373
+ image.save(buffered, format="PNG")
374
+ img_str = base64.b64encode(buffered.getvalue()).decode()
375
+ base64_images.append(img_str)
376
+
377
+ # Get top predicted styles and colors
378
+ top_styles = []
379
+ top_colors = []
380
+
381
+ for style_pred in style_preds:
382
+ top_indices = np.argsort(style_pred)[-2:]
383
+ top_styles.append([Config.STYLE_CATEGORIES[i] for i in top_indices])
384
+ top_colors = [[Config.COLOR_CATEGORIES[i] for i in np.argsort(color_pred)[-2:]] for color_pred in color_preds]
385
+
386
+ return GenerationResponse(
387
+ success=True,
388
+ message=f"Successfully generated {len(images)} mockups")
389
+ generated_images=base64_images,
390
+ predicted_styles=top_styles,
391
+ predicted_colors=top_colors
392
+ )
393
+
394
+ except Exception as e:
395
+ raise HTTPException(status_code=500, detail=f"Generation error: {str(e)}")
396
+
397
+ @app.get("/api/health")
398
+ async def health_check():
399
+ return {"status": "healthy", "service": "ecommerce_image_generator"}
400
+
401
+ def main():
402
+ """Main execution function"""
403
+ print("="*60)
404
+ print("AI FORGE E-COMMERCE IMAGE GENERATOR")
405
+ print("Optimized for 220% YoY demand growth")
406
+ print("="*60)
407
+
408
+ # Initialize and test the system
409
+ system = EcommerceImageAPI()
410
+ system.initialize_system()
411
+
412
+ # Sample generation
413
+ print("\nGenerating sample mockups...")
414
+
415
+ sample_customer_data = [
416
+ {
417
+ 'age': 35,
418
+ 'income_level': 4,
419
+ 'location_urban': 1,
420
+ 'gender_encoded': 0,
421
+ 'region': 'north_america',
422
+ 'device_type': 'mobile',
423
+ 'marketing_channel': 'social_media',
424
+ 'price': 89.99,
425
+ 'category_encoded': 2,
426
+ 'brand_popularity': 8
427
+ }
428
+ ]
429
+
430
+ sample_prompts = [
431
+ "professional product mockup for modern e-commerce website"
432
+ ]
433
+
434
+ images, styles, colors = system.predict_and_generate(
435
+ pd.DataFrame(sample_customer_data),
436
+ sample_prompts
437
+ )
438
+
439
+ print(f"Generated {len(images)} images successfully")
440
+ print(f"Predicted top styles: {styles}")
441
+ print(f"Predicted top colors: {colors}")
442
+
443
+ # Save sample images
444
+ os.makedirs(Config.OUTPUT_DIR, exist_ok=True)
445
+
446
+ for i, image in enumerate(images):
447
+ image_path = os.path.join(Config.OUTPUT_DIR, f"sample_mockup_{i+1}.png")
448
+ image.save(image_path)
449
+ print(f"Saved sample image: {image_path}")
450
+
451
+ print("\nSystem ready for production deployment!")
452
+ print("API endpoints available at http://localhost:8000")
453
+
454
+ if __name__ == "__main__":
455
+ # Run the main function for testing
456
+ main()
457
+
458
+ # Start the FastAPI server
459
+ uvicorn.run(
460
+ "ecommerce_image_generator:app",
461
+ host="0.0.0.0",
462
+ port=8000,
463
+ reload=True
464
+ )
465
+ ```