Humphreykowl commited on
Commit
880ef76
·
verified ·
1 Parent(s): 4badad0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +321 -190
app.py CHANGED
@@ -1,14 +1,14 @@
1
- # app.py (Gradio界面) - 优化版
2
  import gradio as gr
3
  import os
4
  import sys
5
  import logging
6
  from PIL import Image
7
  import numpy as np
8
- from sklearn.cluster import KMeans
9
  import time
10
  import random
11
  import warnings
 
12
 
13
  # 设置环境变量解决 OpenMP 问题
14
  os.environ['OMP_NUM_THREADS'] = '1'
@@ -25,6 +25,7 @@ logger = logging.getLogger(__name__)
25
  try:
26
  from models.model_manager import ModelManager
27
  MODELS_AVAILABLE = True
 
28
  except ImportError as e:
29
  logger.warning(f"模型管理器导入失败: {e}")
30
  logger.info("将使用简化版本运行")
@@ -40,6 +41,9 @@ class SimpleModelManager:
40
  def generate_caption(self, image):
41
  return "这是一件时尚的服装设计,具有现代感和优雅的风格。"
42
 
 
 
 
43
  def generate_image(self, prompt, **kwargs):
44
  # 创建占位图像
45
  width, height = kwargs.get('width', 512), kwargs.get('height', 512)
@@ -50,7 +54,18 @@ class SimpleModelManager:
50
  def cleanup(self):
51
  pass
52
 
53
- # 根据是否有模型选择管理器
 
 
 
 
 
 
 
 
 
 
 
54
  if MODELS_AVAILABLE:
55
  try:
56
  model_manager = ModelManager()
@@ -61,80 +76,125 @@ if MODELS_AVAILABLE:
61
  else:
62
  model_manager = SimpleModelManager()
63
 
64
- def upload_and_analyze(image_path):
65
- """分析上传的图片"""
 
 
66
  try:
67
  if image_path is None:
68
- return {}, {}, gr.Radio(choices=[])
69
 
70
- # 打开图片
 
 
71
  image = Image.open(image_path).convert('RGB')
 
 
 
72
 
73
- # 生成图像描述
74
  try:
75
  caption = model_manager.generate_caption(image)
 
 
76
  except Exception as e:
77
  logger.error(f"生成描述失败: {e}")
78
  caption = "时尚服装设计"
 
79
 
80
- # 基于图像描述进行智能分析
81
- analysis_result = analyze_image_content(image, caption)
82
 
83
- # 基于分析结果生成个性化建议
84
- suggestions = generate_personalized_suggestions(analysis_result, caption)
85
-
86
- # 创建选择选项
87
- choices = list(suggestions.keys())
 
 
 
 
 
 
88
 
89
- return analysis_result, suggestions, gr.Radio(choices=choices, value=choices[0] if choices else None)
90
 
91
- except Exception as e:
92
- error_result = {"错误": f"分析失败: {str(e)}"}
93
- logger.error(f"上传分析失败: {e}")
94
- return error_result, {}, gr.Radio(choices=[])
95
-
96
- def analyze_image_content(image, caption):
97
- """基于图像和描述进行深度分析"""
98
- try:
99
- # 分析图像颜色
100
  colors = extract_dominant_colors(image)
101
 
102
- # 根据描述推断风格类型
103
- style_type = infer_style_from_caption(caption)
104
 
105
- # 根据描述推断服装类别
106
- clothing_category = infer_clothing_category(caption)
107
-
108
- # 根据风格推荐适合场景
109
- suitable_scenes = get_suitable_scenes(style_type)
110
-
111
- return {
112
  "图像描述": caption,
113
- "检测到的颜色": colors,
114
- "风格类型": style_type,
115
- "服装类别": clothing_category,
116
- "适合场景": suitable_scenes,
117
  "图像尺寸": f"{image.width} x {image.height}",
118
  "分析时间": time.strftime("%Y-%m-%d %H:%M:%S")
119
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  except Exception as e:
121
- logger.error(f"图像内容分析失败: {e}")
122
- return {
123
- "错误": f"分析失败: {str(e)}",
124
- "图像描述": caption,
125
- "风格类型": "休闲风"
126
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  def extract_dominant_colors(image):
129
  """提取图像主要颜色"""
130
  try:
 
 
131
  # 调整图像大小以提高处理速度
132
  image = image.resize((150, 150))
133
 
134
  # 转换为numpy数组
135
  img_array = np.array(image)
136
-
137
- # 重塑为颜色列表
138
  pixels = img_array.reshape(-1, 3)
139
 
140
  # 使用KMeans聚类找到主要颜色
@@ -142,12 +202,12 @@ def extract_dominant_colors(image):
142
  kmeans.fit(pixels)
143
 
144
  # 将RGB值转换为颜色名称
145
- color_names = []
146
  for color in kmeans.cluster_centers_:
147
  color_name = rgb_to_color_name(color)
148
- color_names.append(color_name)
149
 
150
- return color_names
151
  except Exception as e:
152
  logger.error(f"颜色提取失败: {e}")
153
  return ["主色调", "辅助色", "点缀色"]
@@ -157,11 +217,10 @@ def rgb_to_color_name(rgb):
157
  try:
158
  r, g, b = rgb.astype(int)
159
 
160
- # 简单的颜色映射
161
  if r > 200 and g > 200 and b > 200:
162
- return "白色"
163
  elif r < 50 and g < 50 and b < 50:
164
- return "黑色"
165
  elif r > g and r > b:
166
  return "红色系" if r > 150 else "深红色系"
167
  elif g > r and g > b:
@@ -177,169 +236,177 @@ def rgb_to_color_name(rgb):
177
  else:
178
  return "灰色系"
179
  except:
180
- return "未知色调"
181
 
182
- def infer_style_from_caption(caption):
183
- """根据图像描述推断风格类型"""
184
- caption_lower = caption.lower()
185
-
186
- style_keywords = {
187
- "商务正装": ["suit", "formal", "business", "office", "professional", "tie", "blazer", "西装", "正装", "商务"],
188
- "休闲风": ["casual", "relaxed", "comfortable", "everyday", "jeans", "t-shirt", "休闲", "日常"],
189
- "运动风": ["sport", "athletic", "gym", "fitness", "running", "training", "运动", "健身"],
190
- "时尚潮流": ["fashion", "trendy", "stylish", "modern", "chic", "designer", "时尚", "潮流"],
191
- "复古风": ["vintage", "retro", "classic", "traditional", "old-fashioned", "复古", "经典"],
192
- "街头风": ["street", "urban", "hip-hop", "cool", "edgy", "街头", "嘻哈"],
193
- "优雅风": ["elegant", "sophisticated", "graceful", "refined", "classy", "优雅", "高贵"]
194
- }
195
-
196
- for style, keywords in style_keywords.items():
197
- if any(keyword in caption_lower for keyword in keywords):
198
- return style
199
-
200
- return "休闲风" # 默认风格
201
-
202
- def infer_clothing_category(caption):
203
- """根据描述推断服装类别"""
204
- caption_lower = caption.lower()
205
-
206
- categories = {
207
- "上衣": ["shirt", "blouse", "top", "jacket", "sweater", "hoodie", "blazer", "衬衫", "上衣", "外套"],
208
- "下装": ["pants", "jeans", "skirt", "shorts", "trousers", "裤子", "短裤", "裙子"],
209
- "连衣裙": ["dress", "gown", "frock", "连衣裙", "礼服"],
210
- "外套": ["coat", "jacket", "cardigan", "blazer", "外套", "大衣"],
211
- "配饰": ["hat", "bag", "shoes", "belt", "jewelry", "帽子", "包", "鞋子", "配饰"],
212
- "全套搭配": ["outfit", "ensemble", "look", "style", "搭配", "整套"]
213
- }
214
-
215
- for category, keywords in categories.items():
216
- if any(keyword in caption_lower for keyword in keywords):
217
- return category
218
-
219
- return "服装单品" # 默认类别
220
-
221
- def get_suitable_scenes(style_type):
222
- """根据风格类型推荐适合场景"""
223
- scene_mapping = {
224
- "商务正装": ["办公室", "商务会议", "正式场合", "面试"],
225
- "休闲风": ["日常出街", "朋友聚会", "购物", "咖啡约会"],
226
- "运动风": ["健身房", "运动", "户外活动", "晨跑"],
227
- "时尚潮流": ["时尚派对", "约会", "拍照", "社交活动"],
228
- "复古风": ["艺术展", "文艺活动", "复古主题活动", "拍摄"],
229
- "街头风": ["街拍", "音乐节", "朋友聚会", "潮流活动"],
230
- "优雅风": ["晚宴", "正式聚会", "典礼", "高端场所"]
231
- }
232
-
233
- return scene_mapping.get(style_type, ["日常", "休闲", "约会"])
234
-
235
- def generate_personalized_suggestions(analysis_result, caption):
236
- """基于分析结果生成个性化建议"""
237
  try:
238
- style_type = analysis_result.get("风格类型", "休闲风")
239
- clothing_category = analysis_result.get("服装类别", "服装单品")
240
- colors = analysis_result.get("检测到的颜色", ["主色调"])
241
 
 
242
  suggestions = {}
243
 
244
- # 根据检测到的风格生成建议
245
- if style_type == "商务正装":
246
  suggestions = {
247
- "经典商务": f"保持{style_type}特色,搭配{colors[0]}系配饰",
248
- "现代商务": f"在{style_type}基础上加入现代元素",
249
- "休闲商务": f"{style_type}与休闲元素结合",
250
- "时尚商务": f"{style_type}融入时尚潮流元素"
251
  }
252
- elif style_type == "休闲风":
253
  suggestions = {
254
- "舒适休闲": f"强化{style_type}的舒适感,主色调{colors[0]}",
255
- "时尚休闲": f"{style_type}加入时尚元素",
256
- "运动休闲": f"{style_type}融入运动风格",
257
- "优雅休闲": f"{style_type}提升优雅感"
258
  }
259
- elif style_type == "运动风":
260
  suggestions = {
261
- "专业运动": f"增强{style_type}的功能性",
262
- "休闲运动": f"{style_type}与日常穿着结合",
263
- "时尚运动": f"{style_type}加入潮流设计元素",
264
- "户外运动": f"强化{style_type}的户外适应性"
265
  }
266
  else:
 
267
  suggestions = {
268
- f"经典{style_type}": f"保持原有{style_type}特色",
269
- f"现代{style_type}": f"{style_type}加入现代元素",
270
- f"融合风格": f"{style_type}与其他风格混搭",
271
- f"个性化{style_type}": f"基于{colors[0]}色调的个性化{style_type}"
272
  }
273
 
274
- return suggestions
 
 
 
 
 
 
 
 
 
 
275
  except Exception as e:
276
  logger.error(f"生成建议失败: {e}")
277
  return {
278
  "经典设计": "传统经典的设计风格",
279
  "现代风格": "融入现代设计元素",
 
280
  "个性化": "独特的个性化设计"
281
  }
282
 
283
  def generate_designs(selected_suggestion, progress=gr.Progress()):
284
- """根据选择的建议生成设计"""
285
  try:
286
  if not selected_suggestion:
287
- return [], gr.Radio(choices=[])
288
-
289
- progress(0.1, desc="准备设计提示...")
290
-
291
- # 生成设计图像的提示词
292
- design_prompts = {
293
- "经典商务": "professional business suit, modern cut, high-quality fabric, clean lines, neutral colors",
294
- "现代商务": "contemporary business attire, innovative design, slim fit, premium materials",
295
- "休闲商务": "business casual outfit, comfortable yet professional, versatile style",
296
- "时尚商务": "fashion-forward business wear, runway inspired, statement piece",
297
- "舒适休闲": "casual comfort wear, soft fabrics, relaxed fit, everyday style",
298
- "时尚休闲": "stylish casual outfit, trendy elements, urban chic",
299
- "运动休闲": "athleisure wear, sporty elements, comfortable and functional",
300
- "优雅休闲": "elegant casual attire, sophisticated details, refined look"
301
- }
302
 
303
- prompt = design_prompts.get(selected_suggestion, "fashion design, stylish clothing")
 
 
 
 
304
 
305
  # 生成设计图像
306
  design_images = []
307
  design_choices = []
308
 
309
- for i in range(3): # 生成3个设计
310
  try:
311
  progress(0.2 + i*0.25, desc=f"生成设计方案 {i+1}/3...")
312
 
313
- # 生成设计图像
 
 
 
314
  image = model_manager.generate_image(
315
- prompt=f"{prompt}, design {i+1}, high detail, fashion illustration",
316
- negative_prompt="blurry, low quality, distorted, text, watermark",
317
- num_inference_steps=20, # 减少步数以提高速度
318
  width=512,
319
- height=512
 
320
  )
321
 
322
  if image:
323
  design_images.append(image)
324
- design_choices.append(f"{selected_suggestion} 设计方案 {i+1}")
 
325
 
326
  except Exception as e:
327
  logger.error(f"生成设计 {i+1} 失败: {e}")
328
  # 创建占位图像
329
  width, height = 512, 512
330
- img = Image.new('RGB', (width, height),
331
- color=(random.randint(100, 200),
332
- random.randint(100, 200),
333
- random.randint(100, 200)))
334
  design_images.append(img)
335
- design_choices.append(f"{selected_suggestion} 设计方案 {i+1}")
 
 
 
336
 
337
  progress(0.95, desc="完成设计生成")
338
- return design_images, gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
 
 
 
 
339
 
340
  except Exception as e:
341
  logger.error(f"设计生成错误: {e}")
342
- return [], gr.Radio(choices=[])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  def generate_3d_fitting(selected_design, progress=gr.Progress()):
345
  """生成3D试穿效果"""
@@ -349,18 +416,39 @@ def generate_3d_fitting(selected_design, progress=gr.Progress()):
349
 
350
  progress(0.1, desc="准备3D试穿...")
351
 
352
- # 生成3D试穿效果的提示词
353
- fitting_prompt = f"3D fashion fitting, virtual try-on, {selected_design}, realistic human model, full body, studio lighting"
 
 
 
 
 
354
 
355
- progress(0.5, desc="生成3D效果...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
- # 生成图像
 
358
  image = model_manager.generate_image(
359
  prompt=fitting_prompt,
360
- negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs",
361
- num_inference_steps=25,
362
  width=512,
363
- height=768 # 适合全身图像
 
364
  )
365
 
366
  progress(0.9, desc="完成3D渲染")
@@ -369,46 +457,78 @@ def generate_3d_fitting(selected_design, progress=gr.Progress()):
369
  except Exception as e:
370
  logger.error(f"3D试穿生成错误: {e}")
371
  # 创建占位图像
372
- img = Image.new('RGB', (512, 768), color=(200, 200, 200))
373
  return img
374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  def create_gradio_interface():
376
  """创建Gradio用户界面"""
377
 
378
  with gr.Blocks(title="AI时尚设计师", theme="soft") as demo:
379
  gr.Markdown("# 🎨 AI时尚设计师")
380
- gr.Markdown("上传图片,获得专业的服装设计建议和3D试穿效果")
381
 
382
  with gr.Row():
383
  with gr.Column(scale=1):
384
  image_input = gr.Image(type="filepath", label="上传参考图片", height=400)
385
- analyze_btn = gr.Button("分析风格", variant="primary")
386
 
387
  with gr.Column(scale=2):
388
- analysis_output = gr.JSON(label="风格分析结果")
389
 
390
- with gr.Tab("设计建议"):
391
  suggestions_output = gr.JSON(label="个性化设计建议")
392
  suggestion_choice = gr.Radio(label="选择设计方向", interactive=True)
393
- generate_designs_btn = gr.Button("生成设计方案", variant="primary")
394
 
395
- with gr.Tab("样衣设计"):
396
- designs_gallery = gr.Gallery(label="样衣设计图", columns=3, height=400)
397
  design_choice = gr.Radio(label="选择设计方案", interactive=True)
398
- generate_3d_btn = gr.Button("生成3D试穿效果", variant="primary")
399
-
400
- with gr.Tab("3D试穿效果"):
401
- fitting_result = gr.Image(label="3D试穿效果", height=500)
402
 
403
- # 内存管理
 
 
 
404
  with gr.Row():
405
- cleanup_btn = gr.Button("清理内存", variant="secondary")
 
 
 
406
 
407
- # 事件绑定 - 使用新的 concurrency_limit 参数
408
  analyze_btn.click(
409
  fn=upload_and_analyze,
410
  inputs=[image_input],
411
- outputs=[analysis_output, suggestions_output, suggestion_choice],
412
  concurrency_limit=1
413
  )
414
 
@@ -432,7 +552,17 @@ def create_gradio_interface():
432
  outputs=[]
433
  )
434
 
435
- gr.Markdown("> **提示**: 如果遇到内存问题,请点击'清理内存'按钮")
 
 
 
 
 
 
 
 
 
 
436
 
437
  return demo
438
 
@@ -440,15 +570,16 @@ if __name__ == "__main__":
440
  # 检查环境
441
  logger.info(f"Python版本: {sys.version}")
442
  logger.info(f"当前工作目录: {os.getcwd()}")
 
443
 
444
  # 创建并启动界面
445
  demo = create_gradio_interface()
446
 
447
- # 启动应用 - 移除废弃的 queue 配置
448
  demo.launch(
449
  server_name="0.0.0.0",
450
  server_port=7860,
451
- share=False, # 在Spaces环境中设为False
452
  show_error=True,
453
- max_threads=2 # 限制线程数
454
  )
 
1
+ # app.py - 完整连接版本
2
  import gradio as gr
3
  import os
4
  import sys
5
  import logging
6
  from PIL import Image
7
  import numpy as np
 
8
  import time
9
  import random
10
  import warnings
11
+ import json
12
 
13
  # 设置环境变量解决 OpenMP 问题
14
  os.environ['OMP_NUM_THREADS'] = '1'
 
25
  try:
26
  from models.model_manager import ModelManager
27
  MODELS_AVAILABLE = True
28
+ logger.info("模型管理器导入成功")
29
  except ImportError as e:
30
  logger.warning(f"模型管理器导入失败: {e}")
31
  logger.info("将使用简化版本运行")
 
41
  def generate_caption(self, image):
42
  return "这是一件时尚的服装设计,具有现代感和优雅的风格。"
43
 
44
+ def analyze_style(self, image):
45
+ return {"时尚潮流": 0.8, "休闲风": 0.6, "优雅风": 0.4}
46
+
47
  def generate_image(self, prompt, **kwargs):
48
  # 创建占位图像
49
  width, height = kwargs.get('width', 512), kwargs.get('height', 512)
 
54
  def cleanup(self):
55
  pass
56
 
57
+ # 全局状态管理
58
+ class AppState:
59
+ def __init__(self):
60
+ self.current_image = None
61
+ self.current_caption = ""
62
+ self.current_analysis = {}
63
+ self.current_suggestions = {}
64
+ self.design_images = []
65
+ self.selected_suggestion = ""
66
+ self.selected_design = ""
67
+
68
+ # 初始化
69
  if MODELS_AVAILABLE:
70
  try:
71
  model_manager = ModelManager()
 
76
  else:
77
  model_manager = SimpleModelManager()
78
 
79
+ app_state = AppState()
80
+
81
+ def upload_and_analyze(image_path, progress=gr.Progress()):
82
+ """完整的图片上传和分析流程"""
83
  try:
84
  if image_path is None:
85
+ return {}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
86
 
87
+ progress(0.1, desc="加载图片...")
88
+
89
+ # 打开并保存图片
90
  image = Image.open(image_path).convert('RGB')
91
+ app_state.current_image = image
92
+
93
+ progress(0.2, desc="生成图像描述...")
94
 
95
+ # 步骤1: 使用模型生成图像描述
96
  try:
97
  caption = model_manager.generate_caption(image)
98
+ app_state.current_caption = caption
99
+ logger.info(f"生成的图像描述: {caption}")
100
  except Exception as e:
101
  logger.error(f"生成描述失败: {e}")
102
  caption = "时尚服装设计"
103
+ app_state.current_caption = caption
104
 
105
+ progress(0.4, desc="分析服装风格...")
 
106
 
107
+ # 步骤2: 使用CLIP模型分析风格
108
+ try:
109
+ if hasattr(model_manager, 'analyze_style'):
110
+ style_scores = model_manager.analyze_style(image)
111
+ else:
112
+ # 回退到基于描述的分析
113
+ style_scores = analyze_style_from_caption(caption)
114
+ logger.info(f"风格分析结果: {style_scores}")
115
+ except Exception as e:
116
+ logger.error(f"风格分析失败: {e}")
117
+ style_scores = {"时尚潮流": 0.8, "休闲风": 0.6}
118
 
119
+ progress(0.6, desc="提取颜色信息...")
120
 
121
+ # 步骤3: 提取颜色信息
 
 
 
 
 
 
 
 
122
  colors = extract_dominant_colors(image)
123
 
124
+ progress(0.8, desc="生成完整分析...")
 
125
 
126
+ # 步骤4: 整合分析结果
127
+ analysis_result = {
 
 
 
 
 
128
  "图像描述": caption,
129
+ "主要风格": max(style_scores.keys(), key=style_scores.get),
130
+ "风格评分": style_scores,
131
+ "主要颜色": colors,
 
132
  "图像尺寸": f"{image.width} x {image.height}",
133
  "分析时间": time.strftime("%Y-%m-%d %H:%M:%S")
134
  }
135
+
136
+ # 步骤5: 基于模型分析结果生成个性化建议
137
+ suggestions = generate_personalized_suggestions_v2(
138
+ caption, style_scores, colors
139
+ )
140
+
141
+ # 保存状态
142
+ app_state.current_analysis = analysis_result
143
+ app_state.current_suggestions = suggestions
144
+
145
+ # 创建建议选项
146
+ choices = list(suggestions.keys())
147
+
148
+ progress(1.0, desc="分析完成")
149
+
150
+ return (
151
+ analysis_result,
152
+ suggestions,
153
+ gr.Radio(choices=choices, value=choices[0] if choices else None),
154
+ gr.Gallery(value=[]) # 清空之前的设计
155
+ )
156
+
157
  except Exception as e:
158
+ error_result = {"错误": f"分析失败: {str(e)}"}
159
+ logger.error(f"上传分析失败: {e}")
160
+ return error_result, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
161
+
162
+ def analyze_style_from_caption(caption):
163
+ """基于描述分析风格(回退方案)"""
164
+ caption_lower = caption.lower()
165
+
166
+ style_keywords = {
167
+ "商务正装": ["suit", "formal", "business", "office", "professional", "tie", "blazer", "西装", "正装", "商务"],
168
+ "休闲风": ["casual", "relaxed", "comfortable", "everyday", "jeans", "t-shirt", "休闲", "日常"],
169
+ "运动风": ["sport", "athletic", "gym", "fitness", "running", "training", "运动", "健身"],
170
+ "时尚潮流": ["fashion", "trendy", "stylish", "modern", "chic", "designer", "时尚", "潮流"],
171
+ "复古风": ["vintage", "retro", "classic", "traditional", "old-fashioned", "复古", "经典"],
172
+ "街头风": ["street", "urban", "hip-hop", "cool", "edgy", "街头", "嘻哈"],
173
+ "优雅风": ["elegant", "sophisticated", "graceful", "refined", "classy", "优雅", "高贵"]
174
+ }
175
+
176
+ style_scores = {}
177
+ for style, keywords in style_keywords.items():
178
+ score = sum(0.2 for keyword in keywords if keyword in caption_lower)
179
+ if score > 0:
180
+ style_scores[style] = min(score, 1.0)
181
+
182
+ # 如果没有匹配,给默认评分
183
+ if not style_scores:
184
+ style_scores = {"休闲风": 0.7, "时尚潮流": 0.5}
185
+
186
+ return style_scores
187
 
188
  def extract_dominant_colors(image):
189
  """提取图像主要颜色"""
190
  try:
191
+ from sklearn.cluster import KMeans
192
+
193
  # 调整图像大小以提高处理速度
194
  image = image.resize((150, 150))
195
 
196
  # 转换为numpy数组
197
  img_array = np.array(image)
 
 
198
  pixels = img_array.reshape(-1, 3)
199
 
200
  # 使用KMeans聚类找到主要颜色
 
202
  kmeans.fit(pixels)
203
 
204
  # 将RGB值转换为颜色名称
205
+ colors = []
206
  for color in kmeans.cluster_centers_:
207
  color_name = rgb_to_color_name(color)
208
+ colors.append(color_name)
209
 
210
+ return colors
211
  except Exception as e:
212
  logger.error(f"颜色提取失败: {e}")
213
  return ["主色调", "辅助色", "点缀色"]
 
217
  try:
218
  r, g, b = rgb.astype(int)
219
 
 
220
  if r > 200 and g > 200 and b > 200:
221
+ return "白色系"
222
  elif r < 50 and g < 50 and b < 50:
223
+ return "黑色系"
224
  elif r > g and r > b:
225
  return "红色系" if r > 150 else "深红色系"
226
  elif g > r and g > b:
 
236
  else:
237
  return "灰色系"
238
  except:
239
+ return "混合色调"
240
 
241
+ def generate_personalized_suggestions_v2(caption, style_scores, colors):
242
+ """基于模型分析结果生成个性化建议"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  try:
244
+ # 获取主要风格
245
+ main_style = max(style_scores.keys(), key=style_scores.get) if style_scores else "时尚潮流"
246
+ main_color = colors[0] if colors else "经典色"
247
 
248
+ # 基于主要风格和颜色生成建议
249
  suggestions = {}
250
 
251
+ if "商务" in main_style:
 
252
  suggestions = {
253
+ f"经典{main_style}": f"保持{main_style}特色,强调{main_color}的专业感",
254
+ f"现代{main_style}": f"在{main_style}基础上融入现代设计元素",
255
+ f"时尚{main_style}": f"{main_style}结合当下流行趋势",
256
+ f"个性{main_style}": f"基于{main_color}打造独特的{main_style}风格"
257
  }
258
+ elif "休闲" in main_style:
259
  suggestions = {
260
+ "舒适休闲": f"强化舒适感,突出{main_color}的自然魅力",
261
+ "时尚休闲": f"休闲风格融入时尚元素",
262
+ "运动休闲": f"结合运动风格的休闲设计",
263
+ "优雅休闲": f"提升休闲装的优雅度"
264
  }
265
+ elif "运动" in main_style:
266
  suggestions = {
267
+ "专业运动": f"强化功能性,突出{main_color}的活力",
268
+ "时尚运动": f"运动风格加入潮流设计",
269
+ "休闲运动": f"适合日常的运动休闲风",
270
+ "户外运动": f"适应户外环境的运动设��"
271
  }
272
  else:
273
+ # 其他风格的通用建议
274
  suggestions = {
275
+ f"经典{main_style}": f"保持{main_style}的经典特色",
276
+ f"现代{main_style}": f"{main_style}融入现代设计理念",
277
+ f"创新{main_style}": f"{main_style}基础上的创新尝试",
278
+ f"个性{main_style}": f"基于{main_color}的个性化{main_style}"
279
  }
280
 
281
+ # 添加基于颜色的额外建议
282
+ color_suggestions = {
283
+ f"单色系设计": f"围绕{main_color}打造单色系搭配",
284
+ f"撞色搭配": f"以{main_color}为主的撞色设计"
285
+ }
286
+
287
+ # 合并建议(限制数量避免选项过多)
288
+ final_suggestions = dict(list(suggestions.items())[:4] + list(color_suggestions.items())[:2])
289
+
290
+ return final_suggestions
291
+
292
  except Exception as e:
293
  logger.error(f"生成建议失败: {e}")
294
  return {
295
  "经典设计": "传统经典的设计风格",
296
  "现代风格": "融入现代设计元素",
297
+ "时尚潮流": "跟随当下时尚趋势",
298
  "个性化": "独特的个性化设计"
299
  }
300
 
301
  def generate_designs(selected_suggestion, progress=gr.Progress()):
302
+ """根据选择的建议使用SD模型生成设计"""
303
  try:
304
  if not selected_suggestion:
305
+ return gr.Gallery(value=[]), gr.Radio(choices=[])
306
+
307
+ progress(0.1, desc="准备设计生成...")
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
+ # 保存选择的建议
310
+ app_state.selected_suggestion = selected_suggestion
311
+
312
+ # 基于当前分析结果和选择的建议生成详细的提示词
313
+ base_prompt = create_design_prompt(selected_suggestion, app_state.current_analysis)
314
 
315
  # 生成设计图像
316
  design_images = []
317
  design_choices = []
318
 
319
+ for i in range(3): # 生成3个设计方案
320
  try:
321
  progress(0.2 + i*0.25, desc=f"生成设计方案 {i+1}/3...")
322
 
323
+ # 为每个设计添加变化
324
+ variant_prompt = f"{base_prompt}, design variation {i+1}, unique style, high quality fashion design"
325
+
326
+ # 使用模型生成图像
327
  image = model_manager.generate_image(
328
+ prompt=variant_prompt,
329
+ negative_prompt="blurry, low quality, distorted, text, watermark, ugly, deformed",
330
+ num_inference_steps=25,
331
  width=512,
332
+ height=512,
333
+ guidance_scale=7.5
334
  )
335
 
336
  if image:
337
  design_images.append(image)
338
+ design_choices.append(f"{selected_suggestion} - 方案 {i+1}")
339
+ logger.info(f"成功生成设计方案 {i+1}")
340
 
341
  except Exception as e:
342
  logger.error(f"生成设计 {i+1} 失败: {e}")
343
  # 创建占位图像
344
  width, height = 512, 512
345
+ color = (random.randint(120, 200), random.randint(120, 200), random.randint(120, 200))
346
+ img = Image.new('RGB', (width, height), color=color)
 
 
347
  design_images.append(img)
348
+ design_choices.append(f"{selected_suggestion} - 方案 {i+1} (占位)")
349
+
350
+ # 保存生成的设计
351
+ app_state.design_images = design_images
352
 
353
  progress(0.95, desc="完成设计生成")
354
+
355
+ return (
356
+ gr.Gallery(value=design_images),
357
+ gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
358
+ )
359
 
360
  except Exception as e:
361
  logger.error(f"设计生成错误: {e}")
362
+ return gr.Gallery(value=[]), gr.Radio(choices=[])
363
+
364
+ def create_design_prompt(suggestion, analysis):
365
+ """基于建议和分析创建详细的设计提示词"""
366
+ try:
367
+ # 从分析中提取关键信息
368
+ style_info = analysis.get("主要风格", "时尚")
369
+ colors = analysis.get("主要颜色", ["现代色"])
370
+ description = analysis.get("图像描述", "")
371
+
372
+ # 基础提示词映射
373
+ style_prompts = {
374
+ "商务正装": "professional business attire, formal suit, clean lines, sophisticated",
375
+ "休闲风": "casual clothing, comfortable style, everyday wear, relaxed fit",
376
+ "运动风": "sportswear, athletic clothing, functional design, activewear",
377
+ "时尚潮流": "trendy fashion, stylish clothing, contemporary design, fashionable",
378
+ "复古风": "vintage style, retro fashion, classic design, nostalgic elements",
379
+ "街头风": "streetwear, urban fashion, casual street style, modern youth",
380
+ "优雅风": "elegant clothing, sophisticated style, refined fashion, graceful design"
381
+ }
382
+
383
+ # 获取风格对应的提示词
384
+ style_prompt = style_prompts.get(style_info, "stylish clothing, modern design")
385
+
386
+ # 颜色相关的提示词
387
+ color_prompt = f"color palette inspired by {colors[0] if colors else 'modern colors'}"
388
+
389
+ # 根据建议调整提示词
390
+ if "经典" in suggestion:
391
+ modifier = "timeless, classic design, traditional elements"
392
+ elif "现代" in suggestion:
393
+ modifier = "contemporary, modern aesthetic, innovative design"
394
+ elif "时尚" in suggestion:
395
+ modifier = "fashion-forward, trendy, runway-inspired"
396
+ elif "个性" in suggestion:
397
+ modifier = "unique, personalized, distinctive style"
398
+ else:
399
+ modifier = "high-quality, well-designed, stylish"
400
+
401
+ # 组合完整的提示词
402
+ full_prompt = f"{style_prompt}, {color_prompt}, {modifier}, high detail, professional fashion photography, studio lighting"
403
+
404
+ logger.info(f"生成的设计提示词: {full_prompt}")
405
+ return full_prompt
406
+
407
+ except Exception as e:
408
+ logger.error(f"创建提示词失败: {e}")
409
+ return "stylish clothing design, high quality, professional fashion"
410
 
411
  def generate_3d_fitting(selected_design, progress=gr.Progress()):
412
  """生成3D试穿效果"""
 
416
 
417
  progress(0.1, desc="准备3D试穿...")
418
 
419
+ # 保存选择的设计
420
+ app_state.selected_design = selected_design
421
+
422
+ # 基于选择的设计和原始分析创建3D试穿提示词
423
+ fitting_prompt = create_3d_fitting_prompt(selected_design, app_state.current_analysis)
424
+
425
+ progress(0.3, desc="生成3D模型...")
426
 
427
+ # 尝试使用ControlNet如果可用
428
+ if hasattr(model_manager, 'controlnet_pipeline') and model_manager.controlnet_pipeline:
429
+ try:
430
+ # 使用ControlNet生成更精确的试穿效果
431
+ image = model_manager.generate_controlnet_image(
432
+ image=app_state.current_image, # 使用原始图像作为控制
433
+ prompt=fitting_prompt,
434
+ negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed",
435
+ num_inference_steps=30,
436
+ guidance_scale=8.0
437
+ )
438
+ progress(0.9, desc="完成3D渲染")
439
+ return image
440
+ except Exception as e:
441
+ logger.warning(f"ControlNet生成失败,使用普通SD: {e}")
442
 
443
+ # 回退到普通SD模型
444
+ progress(0.5, desc="使用标准模型生成...")
445
  image = model_manager.generate_image(
446
  prompt=fitting_prompt,
447
+ negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed, bad anatomy",
448
+ num_inference_steps=30,
449
  width=512,
450
+ height=768, # 适合全身图像
451
+ guidance_scale=7.5
452
  )
453
 
454
  progress(0.9, desc="完成3D渲染")
 
457
  except Exception as e:
458
  logger.error(f"3D试穿生成错误: {e}")
459
  # 创建占位图像
460
+ img = Image.new('RGB', (512, 768), color=(180, 180, 180))
461
  return img
462
 
463
+ def create_3d_fitting_prompt(design_info, analysis):
464
+ """创建3D试穿的提示词"""
465
+ try:
466
+ style_info = analysis.get("主要风格", "时尚")
467
+ colors = analysis.get("主要颜色", ["现代色"])
468
+
469
+ # 3D试穿基础提示词
470
+ base_prompt = "3D virtual try-on, realistic human model wearing"
471
+
472
+ # 根据设计信息调整
473
+ if "方案" in design_info:
474
+ design_type = design_info.split(" - ")[0] if " - " in design_info else design_info
475
+ else:
476
+ design_type = design_info
477
+
478
+ # 添加风格和颜色信息
479
+ style_desc = f"{style_info} style clothing"
480
+ color_desc = f"in {colors[0] if colors else 'stylish colors'}"
481
+
482
+ # 完整的3D试穿提示词
483
+ full_prompt = f"{base_prompt} {style_desc} {color_desc}, full body shot, professional studio lighting, high quality 3D rendering, realistic fabric texture, well-fitted clothing"
484
+
485
+ logger.info(f"3D试穿提示词: {full_prompt}")
486
+ return full_prompt
487
+
488
+ except Exception as e:
489
+ logger.error(f"创建3D提示词失败: {e}")
490
+ return "3D virtual fashion try-on, realistic human model, full body, studio lighting"
491
+
492
  def create_gradio_interface():
493
  """创建Gradio用户界面"""
494
 
495
  with gr.Blocks(title="AI时尚设计师", theme="soft") as demo:
496
  gr.Markdown("# 🎨 AI时尚设计师")
497
+ gr.Markdown("上传服装图片,AI将分析风格并生成个性化设计方案和3D试穿效果")
498
 
499
  with gr.Row():
500
  with gr.Column(scale=1):
501
  image_input = gr.Image(type="filepath", label="上传参考图片", height=400)
502
+ analyze_btn = gr.Button("🔍 AI智能分析", variant="primary", size="lg")
503
 
504
  with gr.Column(scale=2):
505
+ analysis_output = gr.JSON(label="🎯 AI分析结果")
506
 
507
+ with gr.Tab("💡 设计建议"):
508
  suggestions_output = gr.JSON(label="个性化设计建议")
509
  suggestion_choice = gr.Radio(label="选择设计方向", interactive=True)
510
+ generate_designs_btn = gr.Button("🎨 生成设计方案", variant="primary")
511
 
512
+ with gr.Tab("👔 样衣设计"):
513
+ designs_gallery = gr.Gallery(label="AI生成的设计方案", columns=3, height=400)
514
  design_choice = gr.Radio(label="选择设计方案", interactive=True)
515
+ generate_3d_btn = gr.Button("🎭 生成3D试穿效果", variant="primary")
 
 
 
516
 
517
+ with gr.Tab("👤 3D试穿效果"):
518
+ fitting_result = gr.Image(label="3D试穿效果", height=600)
519
+
520
+ # 系统状态和控制
521
  with gr.Row():
522
+ with gr.Column():
523
+ gr.Markdown("### 🔧 系统控制")
524
+ cleanup_btn = gr.Button("🧹 清理内存", variant="secondary")
525
+ gr.Markdown("> **提示**: 如果遇到内存问题,请点击清理内存按钮")
526
 
527
+ # 事件绑定 - 完整的流水线连接
528
  analyze_btn.click(
529
  fn=upload_and_analyze,
530
  inputs=[image_input],
531
+ outputs=[analysis_output, suggestions_output, suggestion_choice, designs_gallery],
532
  concurrency_limit=1
533
  )
534
 
 
552
  outputs=[]
553
  )
554
 
555
+ # 添加使用说明
556
+ with gr.Row():
557
+ gr.Markdown("""
558
+ ### 📋 使用流程:
559
+ 1. **上传图片** → 点击"AI智能分析"进行风格识别
560
+ 2. **查看建议** → 在"设计建议"标签中选择心仪的设计方向
561
+ 3. **生成设计** → 点击"生成设计方案"查看AI设计的服装
562
+ 4. **3D试穿** → 选择喜欢的设计,点击"生成3D试穿效果"
563
+
564
+ 💡 **提示**: 每一步都会调用相应的AI模型,请耐心等待生成完成
565
+ """)
566
 
567
  return demo
568
 
 
570
  # 检查环境
571
  logger.info(f"Python版本: {sys.version}")
572
  logger.info(f"当前工作目录: {os.getcwd()}")
573
+ logger.info(f"模型管理器状态: {'完整版' if MODELS_AVAILABLE else '简化版'}")
574
 
575
  # 创建并启动界面
576
  demo = create_gradio_interface()
577
 
578
+ # 启动应用
579
  demo.launch(
580
  server_name="0.0.0.0",
581
  server_port=7860,
582
+ share=False,
583
  show_error=True,
584
+ max_threads=2
585
  )