Humphreykowl commited on
Commit
2c2d2b6
·
verified ·
1 Parent(s): 6f326b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +748 -434
app.py CHANGED
@@ -6,8 +6,9 @@ import random
6
  import warnings
7
  import json
8
  import numpy as np
9
- from PIL import Image
10
- import gradio as gr # 确保在函数定义前导入
 
11
 
12
  # 设置环境变量解决 OpenMP 问题
13
  os.environ['OMP_NUM_THREADS'] = '1'
@@ -38,29 +39,23 @@ class SimpleModelManager:
38
  logger.info("使用简化模型管理器")
39
 
40
  def generate_caption(self, image):
41
- # 真实模拟BLIP模型输出
42
  return "一件时尚的{}服装,采用{}设计".format(
43
  random.choice(["夏季", "冬季", "春秋季"]),
44
  random.choice(["简约", "复古", "现代", "街头"])
45
  )
46
 
47
  def analyze_style(self, image):
48
- # 真实模拟CLIP模型输出
49
  styles = ["商务正装", "休闲风", "运动风", "时尚潮流", "复古风", "街头风", "优雅风"]
50
  scores = {style: random.uniform(0.3, 0.9) for style in random.sample(styles, 3)}
51
  return scores
52
 
53
  def generate_image(self, prompt, **kwargs):
54
- """真实模拟SD模型生成过程"""
55
  width = kwargs.get('width', 512)
56
  height = kwargs.get('height', 512)
57
-
58
- # 创建基于提示词的图像
59
  img = Image.new('RGB', (width, height), color=(200, 200, 200))
60
  return img
61
 
62
  def generate_controlnet_image(self, image, prompt, **kwargs):
63
- """真实模拟ControlNet生成过程"""
64
  return self.generate_image(prompt, width=512, height=768)
65
 
66
  def cleanup(self):
@@ -75,16 +70,35 @@ class SimpleModelManager:
75
  def force_reload_all_models(self):
76
  pass
77
 
78
- # 全局状态管理
79
- class AppState:
80
  def __init__(self):
81
- self.current_image = None
82
- self.current_caption = ""
83
- self.current_analysis = {}
84
- self.current_suggestions = {}
85
- self.design_images = []
86
- self.selected_suggestion = ""
 
 
 
 
 
87
  self.selected_design_index = -1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  # 初始化模型管理器
90
  if MODELS_AVAILABLE:
@@ -97,556 +111,856 @@ if MODELS_AVAILABLE:
97
  else:
98
  model_manager = SimpleModelManager()
99
 
100
- app_state = AppState()
101
 
102
- def upload_and_analyze(image_path, progress=gr.Progress()):
103
- """完整的图片上传和分析流程 - 使用真实模型分析"""
104
  try:
105
- # 重置应用状态
106
- global app_state
107
- app_state = AppState()
108
 
109
- if image_path is None:
110
- return {}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
 
 
111
 
112
- progress(0.1, desc="加载图片...")
113
- image = Image.open(image_path).convert('RGB')
114
- app_state.current_image = image
115
 
116
- # 步骤1: 使用BLIP模型生成图像描述
117
- progress(0.2, desc="生成图像描述...")
118
- try:
119
- caption = model_manager.generate_caption(image)
120
- app_state.current_caption = caption
121
- logger.info(f"BLIP生成的图像描述: {caption}")
122
- except Exception as e:
123
- logger.error(f"生成描述失败: {e}")
124
- caption = "时尚服装设计"
125
- app_state.current_caption = caption
126
 
127
- # 步骤2: 使用CLIP模型分析风格
128
- progress(0.4, desc="分析服装风格...")
129
- try:
130
- style_scores = model_manager.analyze_style(image)
131
- logger.info(f"CLIP风格分析结果: {style_scores}")
132
- except Exception as e:
133
- logger.error(f"风格分析失败: {e}")
134
- # 使用描述回退分析
135
- style_scores = analyze_style_from_caption(caption)
136
-
137
- # 步骤3: 提取颜色信息
138
- progress(0.6, desc="提取颜色信息...")
139
- colors = extract_dominant_colors(image)
140
- logger.info(f"提取的主要颜色: {colors}")
141
-
142
- # 步骤4: 整合分析结果
143
- progress(0.8, desc="生成完整分析...")
144
- app_state.current_analysis = {
145
- "图像描述": caption,
146
- "主要风格": max(style_scores, key=style_scores.get),
147
- "风格评分": style_scores,
148
- "主要颜色": colors,
149
- "图像尺寸": f"{image.width} x {image.height}",
150
- "分析时间": time.strftime("%Y-%m-%d %H:%M:%S")
151
- }
152
 
153
- # 步骤5: 基于所有分析结果生成个性化建议
154
- app_state.current_suggestions = generate_personalized_suggestions_v2(
155
- caption, style_scores, colors
156
- )
157
- logger.info(f"生成的设计建议: {app_state.current_suggestions}")
158
 
159
- # 创建建议选项
160
- choices = list(app_state.current_suggestions.keys())
 
161
 
162
- progress(1.0, desc="分析完成")
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- return (
165
- app_state.current_analysis,
166
- app_state.current_suggestions,
167
- gr.Radio(choices=choices, value=choices[0] if choices else None),
168
- gr.Gallery(value=[]) # 清空之前的设计
169
- )
170
 
171
  except Exception as e:
172
- logger.error(f"上传分析失败: {e}", exc_info=True)
173
- return {"错误": f"分析失败: {str(e)}"}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
 
 
 
 
 
174
 
175
- def analyze_style_from_caption(caption):
176
- """基于描述分析风格(回退方案)"""
177
- caption_lower = caption.lower()
178
 
179
- style_keywords = {
180
- "商务正装": ["suit", "formal", "business", "office", "professional", "tie", "blazer", "西装", "正装", "商务"],
181
- "休闲风": ["casual", "relaxed", "comfortable", "everyday", "jeans", "t-shirt", "休闲", "日常"],
182
- "运动风": ["sport", "athletic", "gym", "fitness", "running", "training", "运动", "健身"],
183
- "时尚潮流": ["fashion", "trendy", "stylish", "modern", "chic", "designer", "时尚", "潮流"],
184
- "复古风": ["vintage", "retro", "classic", "traditional", "old-fashioned", "复古", "经典"],
185
- "街头风": ["street", "urban", "hip-hop", "cool", "edgy", "街头", "嘻哈"],
186
- "优雅风": ["elegant", "sophisticated", "graceful", "refined", "classy", "优雅", "高贵"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  }
188
 
189
- style_scores = {}
190
- for style, keywords in style_keywords.items():
191
- score = sum(0.2 for keyword in keywords if keyword in caption_lower)
192
- if score > 0:
193
- style_scores[style] = min(score, 1.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- # 如果没有匹配,给默认评分
196
- if not style_scores:
197
- style_scores = {"休闲风": 0.7, "时尚潮流": 0.5}
198
 
199
- return style_scores
 
 
 
 
 
 
 
200
 
201
- def extract_dominant_colors(image):
202
- """提取图像主要颜色 - 真实算法"""
203
  try:
204
- from sklearn.cluster import KMeans
205
-
206
- # 调整图像大小以提高处理速度
207
- image = image.resize((150, 150))
208
-
209
- # 转换为numpy数组
210
- img_array = np.array(image)
211
- pixels = img_array.reshape(-1, 3)
212
-
213
- # 使用KMeans聚类找到主要颜色
214
- kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
215
- kmeans.fit(pixels)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
- # 获取主要颜色
218
- colors = []
219
- for color in kmeans.cluster_centers_:
220
- color_name = rgb_to_color_name(color)
221
- colors.append(color_name)
 
 
222
 
223
- return colors
224
  except Exception as e:
225
- logger.error(f"颜色提取失败: {e}")
226
- return ["主色调", "辅助色", "点缀色"]
 
 
 
 
227
 
228
- def rgb_to_color_name(rgb):
229
- """将RGB值转换为颜色名称 - 真实算法"""
230
- try:
231
- r, g, b = rgb.astype(int)
232
-
233
- if r > 200 and g > 200 and b > 200:
234
- return "白色系"
235
- elif r < 50 and g < 50 and b < 50:
236
- return "黑色系"
237
- elif r > g and r > b:
238
- return "红色系" if r > 150 else "深红色系"
239
- elif g > r and g > b:
240
- return "绿色系" if g > 150 else "深绿色系"
241
- elif b > r and b > g:
242
- return "蓝色系" if b > 150 else "深蓝色系"
243
- elif r > 150 and g > 150:
244
- return "黄色系"
245
- elif r > 100 and b > 100:
246
- return "紫色系"
247
- elif g > 100 and b > 100:
248
- return "青色系"
249
- else:
250
- return "灰色系"
251
- except:
252
- return "混合色调"
253
 
254
- def generate_personalized_suggestions_v2(caption, style_scores, colors):
255
- """基于模型分析结果生成个性化建议"""
256
  try:
257
- # 获取主要风格
258
- main_style = max(style_scores.keys(), key=style_scores.get) if style_scores else "时尚潮流"
259
- main_color = colors[0] if colors else "经典色"
260
-
261
- # 基于主要风格和颜色生成建议
262
- suggestions = {}
263
-
264
- if "商务" in main_style:
265
- suggestions = {
266
- f"经典{main_style}": f"保持{main_style}特色,强调{main_color}的专业感",
267
- f"现代{main_style}": f"在{main_style}基础上融入现代设计元素",
268
- f"时尚{main_style}": f"{main_style}结合当下流行趋势",
269
- f"个性{main_style}": f"基于{main_color}打造独特的{main_style}风格"
270
- }
271
- elif "休闲" in main_style:
272
- suggestions = {
273
- "舒适休闲": f"强化舒适感,突出{main_color}的自然魅力",
274
- "时尚休闲": f"休闲风格融入时尚元素",
275
- "运动休闲": f"结合运动风格的休闲设计",
276
- "优雅休闲": f"提升休闲装的优雅度"
277
- }
278
- elif "运动" in main_style:
279
- suggestions = {
280
- "专业运动": f"强化功能性,突出{main_color}的活力",
281
- "时尚运动": f"运动风格加入潮流设计",
282
- "休闲运动": f"适合日常的运动休闲风",
283
- "户外运动": f"适应户外环境的运动设计"
284
- }
285
- else:
286
- # 其他风格的通用建议
287
- suggestions = {
288
- f"经典{main_style}": f"保持{main_style}的经典特色",
289
- f"现代{main_style}": f"{main_style}融入现代设计理念",
290
- f"创新{main_style}": f"在{main_style}基础上的创新尝试",
291
- f"个性{main_style}": f"基于{main_color}的个性化{main_style}"
292
- }
293
 
294
- # 添加基于颜色的额外建议
295
- color_suggestions = {
296
- f"单色系设计": f"围绕{main_color}打造单色系搭配",
297
- f"撞色搭配": f"以{main_color}为主的撞色设计"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  }
299
 
300
- # 合并建议(限制数量避免选项过多)
301
- final_suggestions = dict(list(suggestions.items())[:4] + list(color_suggestions.items())[:2])
302
 
303
- return final_suggestions
 
 
 
 
 
 
 
 
304
 
305
  except Exception as e:
306
- logger.error(f"生成建议失败: {e}")
307
- return {
308
- "经典设计": "传统经典的设计风格",
309
- "现代风格": "融入现代设计元素",
310
- "时尚潮流": "跟随当下时尚趋势",
311
- "个性化": "独特的个性化设计"
312
- }
313
 
314
- def generate_designs(selected_suggestion, progress=gr.Progress()):
315
- """根据选择的建议使用SD模型生成设计"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  try:
317
- if not selected_suggestion or not app_state.current_analysis:
318
  return gr.Gallery(value=[]), gr.Radio(choices=[])
319
 
 
 
320
  progress(0.1, desc="准备设计生成...")
321
- app_state.selected_suggestion = selected_suggestion
322
 
323
- # 基于当前分析结果和选择的建议生成详细的提示词
324
- base_prompt = create_design_prompt(
325
- selected_suggestion,
326
- app_state.current_analysis
327
- )
328
 
329
- # 生成设计图像
330
- design_images = []
 
331
  design_choices = []
332
 
333
- for i in range(3): # 生成3个设计方案
334
  try:
335
- progress(0.2 + i*0.25, desc=f"生成设计方案 {i+1}/3...")
336
 
337
- # 为每个设计添加变化,同时包含原始描述和风格信息
338
- variant_prompt = (
339
- f"{base_prompt}, design variation {i+1}, "
340
- f"inspired by: '{app_state.current_caption}', "
341
- f"style: {app_state.current_analysis['主要风格']}, "
342
- f"colors: {', '.join(app_state.current_analysis['主要颜色'][:2])}"
343
- )
344
 
345
- # 使用模型生成图像
346
- image = model_manager.generate_image(
347
- prompt=variant_prompt,
348
- negative_prompt="blurry, low quality, distorted, text, watermark, ugly, deformed",
349
- num_inference_steps=25,
350
  width=512,
351
- height=512,
352
- guidance_scale=7.5
353
  )
354
 
355
- design_images.append(image)
356
- design_choices.append(f"{selected_suggestion} - 方案 {i+1}")
357
- logger.info(f"成功生成设计方案 {i+1}")
358
-
359
  except Exception as e:
360
- logger.error(f"生成设计 {i+1} 失败: {e}")
361
  # 创建占位图像
362
- img = create_placeholder_image(512, 512)
363
- design_images.append(img)
364
- design_choices.append(f"{selected_suggestion} - 方案 {i+1} (占位)")
365
 
366
- # 保存生成的设计
367
- app_state.design_images = design_images
368
 
369
- progress(0.95, desc="完成设计生成")
370
 
371
  return (
372
- gr.Gallery(value=design_images),
373
  gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
374
  )
375
 
376
  except Exception as e:
377
- logger.error(f"设计生成错误: {e}")
378
  return gr.Gallery(value=[]), gr.Radio(choices=[])
379
 
380
- def generate_3d_fitting(selected_design_index, progress=gr.Progress()):
381
- """生成3D试穿效果 - 使用更精细的模型"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  try:
383
- if not app_state.design_images or not app_state.current_image or selected_design_index is None:
384
  return None
385
 
386
- progress(0.1, desc="准备3D试穿...")
387
 
388
- # 获取选中的设计
389
- selected_image = app_state.design_images[selected_design_index]
390
- app_state.selected_design_index = selected_design_index
391
 
392
- # 基于原���图像和选择的设计创建3D试穿提示词
393
- fitting_prompt = create_3d_fitting_prompt(
394
- selected_design_index,
395
- app_state.current_analysis
396
- )
 
 
 
397
 
398
- progress(0.3, desc="生成3D模型...")
399
 
400
- # 使用更精细的3D模型
401
  try:
402
- # 使用专门的3D试穿模型
403
- image = model_manager.generate_controlnet_image(
404
- image=app_state.current_image, # 使用原始图像作为控制
405
  prompt=fitting_prompt,
406
- reference_image=selected_image, # 设计风格参考
407
- negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed",
408
- num_inference_steps=40, # 更多步骤以获得更高质量
409
  guidance_scale=8.5
410
  )
 
411
  progress(0.9, desc="完成3D渲染")
 
412
  logger.info("使用ControlNet生成3D试穿效果")
413
- return image
 
414
  except Exception as e:
415
- logger.warning(f"3D模型生成失败: {e}")
416
-
417
- # 回退到普通模型
418
- progress(0.5, desc="使用标准模型生成...")
419
- try:
420
- image = model_manager.generate_image(
421
  prompt=fitting_prompt,
422
- negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed, bad anatomy",
423
  num_inference_steps=35,
424
  width=512,
425
  height=768,
426
- guidance_scale=7.5
427
  )
428
- except Exception as e:
429
- logger.error(f"3D试穿生成失败: {e}")
430
- image = create_placeholder_image(512, 768)
431
-
432
- progress(0.9, desc="完成3D渲染")
433
- return image
434
 
435
  except Exception as e:
436
- logger.error(f"3D试穿生成错误: {e}")
437
- return create_placeholder_image(512, 768)
438
 
439
- def create_design_prompt(suggestion, analysis):
440
- """创建详细的设计提示词 - 整合所有分析结果"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
  try:
442
- # 从分析中提取关键信息
443
- style_info = analysis.get("主要风格", "时尚")
444
- colors = analysis.get("主要颜色", ["现代色"])
445
- caption = analysis.get("图像描述", "")
446
-
447
- # 获取风格描述
448
- style_prompts = {
449
- "商务正装": "专业商务装,正式西装,简洁线条,精致剪裁",
450
- "休闲风": "休闲服装,舒适风格,日常穿着,宽松合身",
451
- "运动风": "运动服装,功能性设计,运动休闲",
452
- "时尚潮流": "时尚潮流,现代设计,高级时装",
453
- "复古风": "复古风格,怀旧元素,经典设计",
454
- "街头风": "街头服饰,都市风格,现代青年文化",
455
- "优雅风": "优雅服装,精致风格,高贵设计"
456
- }
457
-
458
- style_prompt = style_prompts.get(style_info, "时尚服装,现代设计")
459
-
460
- # 颜色描述
461
- color_prompt = f"主色调: {colors[0] if colors else '现代色调'}"
462
- if len(colors) > 1:
463
- color_prompt += f", 辅色: {colors[1]}"
464
-
465
- # 根据建议调整提示词
466
- suggestion_modifiers = {
467
- "经典": "经典设计,永恒风格,传统元素",
468
- "现代": "现代美学,创新设计,前沿时尚",
469
- "时尚": "时尚前沿,T台风格,潮流趋势",
470
- "个性": "独特设计,个性化元素,定制风格"
471
- }
472
-
473
- modifier = "高品质,精心设计,时尚风格"
474
- for key, value in suggestion_modifiers.items():
475
- if key in suggestion:
476
- modifier = value
477
- break
478
-
479
- # 组合完整的提示词 - 整合所有分析元素
480
- full_prompt = (
481
- f"{style_prompt},{color_prompt},{modifier}。"
482
- f"设计灵感来源:'{caption}'。"
483
- f"高清细节,专业时尚摄影,工作室灯光"
484
- )
485
-
486
- logger.info(f"生成的设计提示词: {full_prompt}")
487
- return full_prompt
488
-
489
- except Exception as e:
490
- logger.error(f"创建提示词失败: {e}")
491
- return "时尚服装设计,高品质,专业时尚"
492
 
493
- def create_3d_fitting_prompt(design_index, analysis):
494
- """创建3D试穿的提示词 - 整合所有分析结果"""
 
 
 
495
  try:
496
- style_info = analysis.get("主要风格", "时尚")
497
- colors = analysis.get("主要颜色", ["现代色"])
498
- caption = analysis.get("图像描述", "")
499
-
500
- # 获取设计描述
501
- design_desc = f"设计方案 {design_index+1}"
502
-
503
- # 3D试穿基础提示词
504
- base_prompt = "高精度3D虚拟试穿,真实人体模特穿着"
505
-
506
- # 添加风格和颜色信息
507
- style_desc = f"{style_info}风格服装"
508
- color_desc = f"主色调: {colors[0] if colors else '时尚色调'}"
509
-
510
- # 完整的3D试穿提示词
511
- full_prompt = (
512
- f"{base_prompt} {style_desc},{color_desc}。"
513
- f"全身展示,专业工作室灯光,高质量3D渲染,"
514
- f"真实面料质感,合身剪裁,高清细节。"
515
- f"设��灵感:'{caption}'。"
516
- f"具体设计:{design_desc}"
517
- )
 
 
 
 
 
518
 
519
- logger.info(f"3D试穿提示词: {full_prompt}")
520
- return full_prompt
521
 
522
  except Exception as e:
523
- logger.error(f"创建3D提示词失败: {e}")
524
- return "高精度3D虚拟时尚试穿,真实人体模特,全身展示,工作室灯光"
525
-
526
- def create_placeholder_image(width, height):
527
- """创建占位图像 - 修复语法错误"""
528
- color = (random.randint(120, 200), random.randint(120, 200), random.randint(120, 200))
529
- return Image.new('RGB', (width, height), color=color)
530
 
531
  def create_gradio_interface():
532
- """创建Gradio用户界面"""
533
 
534
- with gr.Blocks(title="AI时尚设计师", theme="soft") as demo:
535
- gr.Markdown("# 🎨 AI时尚设计师")
536
- gr.Markdown("上传服装图片,AI将分析风格并生成个性化设计方案和3D试穿效果")
537
 
538
  with gr.Row():
539
  with gr.Column(scale=1):
540
- image_input = gr.Image(type="filepath", label="上传参考图片", height=400)
541
- analyze_btn = gr.Button("🔍 AI智能分析", variant="primary", size="lg")
 
 
 
 
542
 
543
  with gr.Column(scale=2):
544
- analysis_output = gr.JSON(label="🎯 AI分析结果")
545
-
546
- with gr.Tab("💡 设计建议"):
547
- suggestions_output = gr.JSON(label="个性化设计建议")
548
- suggestion_choice = gr.Radio(label="选择设计方向", interactive=True)
549
- generate_designs_btn = gr.Button("🎨 生成设计方案", variant="primary")
550
-
551
- with gr.Tab("👔 样衣设计"):
552
- designs_gallery = gr.Gallery(label="AI生成的设计方案", columns=3, height=400)
553
- design_choice = gr.Radio(label="选择设计方案", type="index", interactive=True)
554
- generate_3d_btn = gr.Button("🎭 生成3D试穿效果", variant="primary")
555
-
556
- with gr.Tab("👤 3D试穿效果"):
557
- fitting_result = gr.Image(label="3D试穿效果", height=600)
558
-
559
- # 系统状态和控制
560
- with gr.Row():
561
- with gr.Column():
562
- gr.Markdown("### 🔧 系统控制")
563
- cleanup_btn = gr.Button("🧹 清理显存缓存", variant="secondary")
564
- cpu_btn = gr.Button("💾 模型移至CPU", variant="secondary")
565
- gpu_btn = gr.Button("🚀 模型移至GPU", variant="secondary")
566
- reload_btn = gr.Button("🔄 重新加载模型", variant="primary")
567
- gr.Markdown("""
568
- > **使用说明**:
569
- > - **清理显存缓存**: 只清理缓存,不影响模型
570
- > - **模型移至CPU**: 释放GPU显存,但推理会变慢
571
- > - **模型移至GPU**: 将模型移回GPU,恢复正常速度
572
- > - **重新加载模型**: 如果模型出现问题,强制重新加载
573
- """)
 
 
 
574
 
575
- # 事件绑定 - 完整的流水线连接
 
 
 
 
 
 
 
 
576
  analyze_btn.click(
577
- fn=upload_and_analyze,
578
  inputs=[image_input],
579
  outputs=[analysis_output, suggestions_output, suggestion_choice, designs_gallery]
580
  )
581
 
582
  generate_designs_btn.click(
583
- fn=generate_designs,
584
  inputs=[suggestion_choice],
585
  outputs=[designs_gallery, design_choice]
586
  )
587
 
588
  generate_3d_btn.click(
589
- fn=generate_3d_fitting,
590
  inputs=[design_choice],
591
  outputs=[fitting_result]
592
  )
593
 
594
- cleanup_btn.click(
595
- fn=model_manager.cleanup,
596
  inputs=[],
597
- outputs=[]
598
  )
599
 
600
- cpu_btn.click(
601
- fn=model_manager.move_models_to_cpu,
602
  inputs=[],
603
- outputs=[]
604
  )
605
 
606
- gpu_btn.click(
607
- fn=model_manager.move_models_to_gpu,
608
- inputs=[],
609
- outputs=[]
610
- )
611
-
612
- reload_btn.click(
613
- fn=model_manager.force_reload_all_models,
614
- inputs=[],
615
- outputs=[]
616
- )
617
 
618
- # 添加使用说明
619
- with gr.Row():
620
  gr.Markdown("""
621
- ### 📋 使用流程:
622
- 1. **上传图片** → 点击"AI智能分析"进行风格识别
623
- 2. **查看建议** → 在"设计建议"标签中选择��仪的设计方向
624
- 3. **生成设计** → 点击"生成设计方案"查看AI设计的服装
625
- 4. **3D试穿** → 选择喜欢的设计,点击"生成3D试穿效果"
626
 
627
- 💡 **提示**:
628
- - 每一步都会调用相应的AI模型,请耐心等待生成完成
629
- - 使用ControlNet模型生成高质量的3D试穿效果
630
- - 所有设计都基于原始图片的分析结果
631
- - 如果遇到模型问题,可以使用下方的系统控制按钮
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
632
  """)
633
 
634
  return demo
635
 
636
  if __name__ == "__main__":
637
- # 检查环境
638
  logger.info(f"Python版本: {sys.version}")
639
  logger.info(f"当前工作目录: {os.getcwd()}")
640
  logger.info(f"模型管理器状态: {'完整版' if MODELS_AVAILABLE else '简化版'}")
641
 
642
- # 创建并启动界面
643
  demo = create_gradio_interface()
644
-
645
- # 启动应用
646
  demo.launch(
647
- server_name="0.0.0.0",
648
  server_port=7860,
649
  share=False,
650
  show_error=True,
651
- max_threads=2
652
  )
 
6
  import warnings
7
  import json
8
  import numpy as np
9
+ from PIL import Image, ImageDraw, ImageFont
10
+ import gradio as gr
11
+ import colorsys
12
 
13
  # 设置环境变量解决 OpenMP 问题
14
  os.environ['OMP_NUM_THREADS'] = '1'
 
39
  logger.info("使用简化模型管理器")
40
 
41
  def generate_caption(self, image):
 
42
  return "一件时尚的{}服装,采用{}设计".format(
43
  random.choice(["夏季", "冬季", "春秋季"]),
44
  random.choice(["简约", "复古", "现代", "街头"])
45
  )
46
 
47
  def analyze_style(self, image):
 
48
  styles = ["商务正装", "休闲风", "运动风", "时尚潮流", "复古风", "街头风", "优雅风"]
49
  scores = {style: random.uniform(0.3, 0.9) for style in random.sample(styles, 3)}
50
  return scores
51
 
52
  def generate_image(self, prompt, **kwargs):
 
53
  width = kwargs.get('width', 512)
54
  height = kwargs.get('height', 512)
 
 
55
  img = Image.new('RGB', (width, height), color=(200, 200, 200))
56
  return img
57
 
58
  def generate_controlnet_image(self, image, prompt, **kwargs):
 
59
  return self.generate_image(prompt, width=512, height=768)
60
 
61
  def cleanup(self):
 
70
  def force_reload_all_models(self):
71
  pass
72
 
73
+ # 改进的全局状态管理
74
+ class DesignState:
75
  def __init__(self):
76
+ self.reset()
77
+
78
+ def reset(self):
79
+ self.original_image = None
80
+ self.image_caption = ""
81
+ self.style_analysis = {}
82
+ self.color_analysis = {}
83
+ self.fabric_analysis = {}
84
+ self.design_direction = ""
85
+ self.design_concepts = []
86
+ self.generated_designs = []
87
  self.selected_design_index = -1
88
+ self.fitting_result = None
89
+
90
+ def get_design_context(self):
91
+ """获取完整的设计上下文,用于生成连贯的设计"""
92
+ return {
93
+ "caption": self.image_caption,
94
+ "main_style": max(self.style_analysis.keys(), key=self.style_analysis.get) if self.style_analysis else "时尚",
95
+ "style_scores": self.style_analysis,
96
+ "dominant_colors": self.color_analysis.get("dominant_colors", []),
97
+ "color_palette": self.color_analysis.get("color_palette", {}),
98
+ "fabric_type": self.fabric_analysis.get("predicted_fabric", "棉质"),
99
+ "texture": self.fabric_analysis.get("texture", "光滑"),
100
+ "design_direction": self.design_direction
101
+ }
102
 
103
  # 初始化模型管理器
104
  if MODELS_AVAILABLE:
 
111
  else:
112
  model_manager = SimpleModelManager()
113
 
114
+ design_state = DesignState()
115
 
116
+ def advanced_color_analysis(image):
117
+ """高级颜色分析 - 提取颜色调色板和情感色彩"""
118
  try:
119
+ from sklearn.cluster import KMeans
 
 
120
 
121
+ # 调整图像大小
122
+ image = image.resize((150, 150))
123
+ img_array = np.array(image)
124
+ pixels = img_array.reshape(-1, 3)
125
 
126
+ # 使用KMeans提取主要颜色
127
+ kmeans = KMeans(n_clusters=5, random_state=42, n_init=10)
128
+ kmeans.fit(pixels)
129
 
130
+ colors = kmeans.cluster_centers_.astype(int)
131
+ labels = kmeans.labels_
 
 
 
 
 
 
 
 
132
 
133
+ # 计算每种颜色的比例
134
+ color_percentages = []
135
+ for i in range(5):
136
+ percentage = np.sum(labels == i) / len(labels)
137
+ color_percentages.append(percentage)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ # 按比例排序
140
+ color_data = list(zip(colors, color_percentages))
141
+ color_data.sort(key=lambda x: x[1], reverse=True)
 
 
142
 
143
+ # 生成颜色信息
144
+ dominant_colors = []
145
+ color_palette = {}
146
 
147
+ for i, (color, percentage) in enumerate(color_data):
148
+ color_name = rgb_to_detailed_color_name(color)
149
+ color_emotion = get_color_emotion(color)
150
+ dominant_colors.append(color_name)
151
+
152
+ color_palette[f"颜色{i+1}"] = {
153
+ "name": color_name,
154
+ "rgb": color.tolist(),
155
+ "hex": rgb_to_hex(color),
156
+ "percentage": f"{percentage:.1%}",
157
+ "emotion": color_emotion,
158
+ "fashion_application": get_fashion_application(color_name)
159
+ }
160
 
161
+ return {
162
+ "dominant_colors": dominant_colors[:3], # 前3种主要颜色
163
+ "color_palette": color_palette,
164
+ "color_harmony": analyze_color_harmony(colors[:3]),
165
+ "season_analysis": analyze_seasonal_colors(colors[:3])
166
+ }
167
 
168
  except Exception as e:
169
+ logger.error(f"高级颜色分析失败: {e}")
170
+ return {
171
+ "dominant_colors": ["经典色调"],
172
+ "color_palette": {"颜色1": {"name": "经典色调", "emotion": "中性"}},
173
+ "color_harmony": "单色调",
174
+ "season_analysis": "四季通用"
175
+ }
176
 
177
+ def rgb_to_detailed_color_name(rgb):
178
+ """更详细的RGB到颜色名称转换"""
179
+ r, g, b = rgb
180
 
181
+ # 转换到HSV空间进行更精确的颜色分类
182
+ h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
183
+ h = h * 360
184
+ s = s * 100
185
+ v = v * 100
186
+
187
+ # 基于HSV值进行精确分类
188
+ if v < 20:
189
+ return "深黑色"
190
+ elif v > 90 and s < 10:
191
+ return "纯白色"
192
+ elif s < 15:
193
+ if v < 30:
194
+ return "深灰色"
195
+ elif v < 70:
196
+ return "中灰色"
197
+ else:
198
+ return "浅灰色"
199
+
200
+ # 彩色分类
201
+ color_ranges = [
202
+ (0, 15, "深红色"), (15, 45, "橙红色"), (45, 75, "金黄色"),
203
+ (75, 105, "草绿色"), (105, 135, "翠绿色"), (135, 165, "青绿色"),
204
+ (165, 195, "天蓝色"), (195, 225, "宝蓝色"), (225, 255, "紫蓝色"),
205
+ (255, 285, "紫色"), (285, 315, "紫红色"), (315, 345, "玫红色"),
206
+ (345, 360, "深红色")
207
+ ]
208
+
209
+ for start, end, color_name in color_ranges:
210
+ if start <= h < end:
211
+ if v < 40:
212
+ return f"深{color_name}"
213
+ elif v > 80:
214
+ return f"亮{color_name}"
215
+ else:
216
+ return color_name
217
+
218
+ return "混合色调"
219
+
220
+ def rgb_to_hex(rgb):
221
+ """RGB转十六进制"""
222
+ return "#{:02x}{:02x}{:02x}".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))
223
+
224
+ def get_color_emotion(rgb):
225
+ """获取颜色的情感属性"""
226
+ r, g, b = rgb
227
+
228
+ # 基于颜色心理学的情感映射
229
+ if r > 180 and g < 100 and b < 100:
230
+ return "热情、力量、激情"
231
+ elif r < 100 and g > 150 and b < 100:
232
+ return "自然、平静、成长"
233
+ elif r < 100 and g < 100 and b > 150:
234
+ return "专业、信任、稳定"
235
+ elif r > 150 and g > 150 and b < 100:
236
+ return "温暖、活力、创意"
237
+ elif r > 100 and g < 100 and b > 150:
238
+ return "神秘、高贵、优雅"
239
+ elif r < 50 and g < 50 and b < 50:
240
+ return "经典、正式、权威"
241
+ elif r > 200 and g > 200 and b > 200:
242
+ return "纯洁、简约、现代"
243
+ else:
244
+ return "平衡、和谐、中性"
245
+
246
+ def get_fashion_application(color_name):
247
+ """获取颜色在时尚中的应用建议"""
248
+ applications = {
249
+ "深红色": "晚装、正装细节、配饰",
250
+ "橙红色": "夏季休闲、运动装、配饰",
251
+ "金黄色": "夏季单品、配饰、装饰细节",
252
+ "草绿色": "春夏装、休闲装、自然风格",
253
+ "翠绿色": "春装、度假装、民族风格",
254
+ "天蓝色": "衬衫、夏装、商务休闲",
255
+ "宝蓝色": "正装、晚装、经典款式",
256
+ "紫色": "晚装、艺术风格、个性单品",
257
+ "深黑色": "基础款、正装、经典设计",
258
+ "纯白色": "基础款、夏装、简约风格",
259
+ "深灰色": "商务装、基础款、现代风格"
260
  }
261
 
262
+ return applications.get(color_name, "通用时尚单品")
263
+
264
+ def analyze_color_harmony(colors):
265
+ """分析颜色和谐度"""
266
+ if len(colors) < 2:
267
+ return "单色调"
268
+
269
+ # 转换为HSV进行分析
270
+ hsv_colors = []
271
+ for color in colors:
272
+ h, s, v = colorsys.rgb_to_hsv(color[0]/255.0, color[1]/255.0, color[2]/255.0)
273
+ hsv_colors.append((h*360, s*100, v*100))
274
+
275
+ h_values = [hsv[0] for hsv in hsv_colors]
276
+
277
+ # 判断配色方案
278
+ h_diff = max(h_values) - min(h_values)
279
+
280
+ if h_diff < 30:
281
+ return "同色系配色"
282
+ elif h_diff < 60:
283
+ return "相邻色配色"
284
+ elif 150 < h_diff < 210:
285
+ return "对比色配色"
286
+ else:
287
+ return "多色调配色"
288
+
289
+ def analyze_seasonal_colors(colors):
290
+ """分析季节色彩倾向"""
291
+ # 计算平均饱和度和明度
292
+ total_s, total_v = 0, 0
293
+
294
+ for color in colors:
295
+ h, s, v = colorsys.rgb_to_hsv(color[0]/255.0, color[1]/255.0, color[2]/255.0)
296
+ total_s += s
297
+ total_v += v
298
 
299
+ avg_s = total_s / len(colors)
300
+ avg_v = total_v / len(colors)
 
301
 
302
+ if avg_s > 0.6 and avg_v > 0.6:
303
+ return "春季色彩(明亮、清新)"
304
+ elif avg_s > 0.6 and avg_v < 0.6:
305
+ return "秋季色彩(浓郁、温暖)"
306
+ elif avg_s < 0.6 and avg_v > 0.6:
307
+ return "夏季色彩(柔和、清淡)"
308
+ else:
309
+ return "冬季色彩(深沉、对比)"
310
 
311
+ def analyze_fabric_texture(image):
312
+ """分析面料和质地(基于图像特征)"""
313
  try:
314
+ # 转换为灰度图进行纹理分析
315
+ gray_image = image.convert('L')
316
+ img_array = np.array(gray_image)
317
+
318
+ # 计算纹理特征
319
+ # 1. 计算标准差(纹理粗糙度)
320
+ texture_variance = np.std(img_array)
321
+
322
+ # 2. 计算边缘密度
323
+ from scipy import ndimage
324
+ edges = ndimage.sobel(img_array)
325
+ edge_density = np.mean(np.abs(edges))
326
+
327
+ # 基于特征推断面料类型
328
+ if texture_variance < 20:
329
+ if edge_density < 10:
330
+ fabric_type = "丝绸"
331
+ texture = "光滑丝滑"
332
+ else:
333
+ fabric_type = "棉质"
334
+ texture = "柔软光滑"
335
+ elif texture_variance < 40:
336
+ fabric_type = "混纺"
337
+ texture = "适中质感"
338
+ else:
339
+ if edge_density > 30:
340
+ fabric_type = "牛仔"
341
+ texture = "粗糙硬挺"
342
+ else:
343
+ fabric_type = "毛呢"
344
+ texture = "厚实温暖"
345
 
346
+ return {
347
+ "predicted_fabric": fabric_type,
348
+ "texture": texture,
349
+ "texture_score": texture_variance,
350
+ "edge_score": edge_density,
351
+ "fabric_properties": get_fabric_properties(fabric_type)
352
+ }
353
 
 
354
  except Exception as e:
355
+ logger.error(f"面料分析失败: {e}")
356
+ return {
357
+ "predicted_fabric": "棉质",
358
+ "texture": "舒适",
359
+ "fabric_properties": "透气、舒适、日常"
360
+ }
361
 
362
+ def get_fabric_properties(fabric_type):
363
+ """获取面料特性"""
364
+ properties = {
365
+ "丝绸": "光泽感强、垂坠性好、高级感、适合正装",
366
+ "棉质": "透气舒适、日常休闲、易打理、四季适用",
367
+ "混纺": "结合优点、性价比高、适应性强、现代感",
368
+ "牛仔": "硬挺耐用、休闲风格、经典时尚、年轻活力",
369
+ "毛呢": "保暖性好、正式高级、秋冬首选、商务感强"
370
+ }
371
+ return properties.get(fabric_type, "舒适实用")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
 
373
+ def comprehensive_image_analysis(image_path, progress=gr.Progress()):
374
+ """综合图像分析 - 整合所有分析维度"""
375
  try:
376
+ design_state.reset()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
+ if image_path is None:
379
+ return {}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
380
+
381
+ progress(0.05, desc="加载图片...")
382
+ image = Image.open(image_path).convert('RGB')
383
+ design_state.original_image = image
384
+
385
+ # 1. BLIP图像描述
386
+ progress(0.15, desc="AI图像理解中...")
387
+ try:
388
+ caption = model_manager.generate_caption(image)
389
+ design_state.image_caption = caption
390
+ logger.info(f"BLIP描述: {caption}")
391
+ except Exception as e:
392
+ logger.error(f"图像描述生成失败: {e}")
393
+ caption = "时尚服装设计作品"
394
+ design_state.image_caption = caption
395
+
396
+ # 2. CLIP风格分析
397
+ progress(0.3, desc="AI风格识别中...")
398
+ try:
399
+ style_scores = model_manager.analyze_style(image)
400
+ design_state.style_analysis = style_scores
401
+ logger.info(f"风格分析: {style_scores}")
402
+ except Exception as e:
403
+ logger.error(f"风格分析失败: {e}")
404
+ style_scores = {"时尚潮流": 0.8, "现代风格": 0.6}
405
+ design_state.style_analysis = style_scores
406
+
407
+ # 3. 高级颜色分析
408
+ progress(0.5, desc="深度颜色分析中...")
409
+ color_analysis = advanced_color_analysis(image)
410
+ design_state.color_analysis = color_analysis
411
+
412
+ # 4. 面料质地分析
413
+ progress(0.7, desc="面料质地分析中...")
414
+ fabric_analysis = analyze_fabric_texture(image)
415
+ design_state.fabric_analysis = fabric_analysis
416
+
417
+ # 5. 生成综合分析报告
418
+ progress(0.85, desc="生成分析报告...")
419
+ comprehensive_analysis = {
420
+ "基础信息": {
421
+ "图像描述": caption,
422
+ "图像尺寸": f"{image.width} x {image.height}",
423
+ "分析时间": time.strftime("%Y-%m-%d %H:%M:%S")
424
+ },
425
+ "风格分析": {
426
+ "主要风格": max(style_scores.keys(), key=style_scores.get),
427
+ "风格置信度": f"{max(style_scores.values()):.1%}",
428
+ "所有风格评分": {k: f"{v:.1%}" for k, v in sorted(style_scores.items(), key=lambda x: x[1], reverse=True)}
429
+ },
430
+ "颜色分析": {
431
+ "主色调": color_analysis["dominant_colors"][0] if color_analysis["dominant_colors"] else "经典色调",
432
+ "配色方案": color_analysis["color_harmony"],
433
+ "季节倾向": color_analysis["season_analysis"],
434
+ "颜色情感": color_analysis["color_palette"].get("颜色1", {}).get("emotion", "中性")
435
+ },
436
+ "材质分析": {
437
+ "预测面料": fabric_analysis["predicted_fabric"],
438
+ "质地特征": fabric_analysis["texture"],
439
+ "面料特性": fabric_analysis["fabric_properties"]
440
+ }
441
  }
442
 
443
+ # 6. 基于综合分析生成设计建议
444
+ design_suggestions = generate_intelligent_suggestions()
445
 
446
+ progress(1.0, desc="分析完成")
447
+
448
+ choices = list(design_suggestions.keys())
449
+ return (
450
+ comprehensive_analysis,
451
+ design_suggestions,
452
+ gr.Radio(choices=choices, value=choices[0] if choices else None),
453
+ gr.Gallery(value=[])
454
+ )
455
 
456
  except Exception as e:
457
+ logger.error(f"综合分析失败: {e}", exc_info=True)
458
+ return {"错误": f"分析失败: {str(e)}"}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
 
 
 
 
 
459
 
460
+ def generate_intelligent_suggestions():
461
+ """基于所有分析维度生成智能设计建议"""
462
+ context = design_state.get_design_context()
463
+
464
+ # 获取关键信息
465
+ main_style = context["main_style"]
466
+ dominant_color = context["dominant_colors"][0] if context["dominant_colors"] else "经典色调"
467
+ fabric_type = context["fabric_type"]
468
+ color_emotion = design_state.color_analysis.get("color_palette", {}).get("颜色1", {}).get("emotion", "中性")
469
+
470
+ # 基于综合分析生成建议
471
+ suggestions = {}
472
+
473
+ # 1. 风格延续建议
474
+ suggestions[f"经典{main_style}"] = f"保持{main_style}核心特色,运用{dominant_color}主色调,体现{color_emotion}的情感表达"
475
+
476
+ # 2. 材质创新建议
477
+ suggestions[f"{fabric_type}质感创新"] = f"基于{fabric_type}面料特性,结合{dominant_color}配色,打造现代{main_style}风格"
478
+
479
+ # 3. 配色方案建议
480
+ color_harmony = design_state.color_analysis.get("color_harmony", "和谐配色")
481
+ suggestions[f"{color_harmony}设计"] = f"采用{color_harmony}策略,以{dominant_color}为主调,营造{color_emotion}氛围"
482
+
483
+ # 4. 季节适应建议
484
+ season_analysis = design_state.color_analysis.get("season_analysis", "四季通用")
485
+ suggestions[f"{season_analysis}款式"] = f"针对{season_analysis}特点,融合{main_style}元素,突出{fabric_type}质感"
486
+
487
+ # 5. 情感导向建议
488
+ suggestions[f"{color_emotion}表达"] = f"强化{color_emotion}的情感传达,通过{main_style}剪裁体现{fabric_type}的独特魅力"
489
+
490
+ # 6. 创新融合建议
491
+ suggestions["跨界融合创新"] = f"打破传统{main_style}界限,创新运用{dominant_color},结合现代设计理念"
492
+
493
+ return suggestions
494
+
495
+ def generate_professional_designs(selected_suggestion, progress=gr.Progress()):
496
+ """生成专业服装设计图 - 三视图风格"""
497
  try:
498
+ if not selected_suggestion or not design_state.original_image:
499
  return gr.Gallery(value=[]), gr.Radio(choices=[])
500
 
501
+ design_state.design_direction = selected_suggestion
502
+
503
  progress(0.1, desc="准备设计生成...")
 
504
 
505
+ # 获取完整设计上下文
506
+ context = design_state.get_design_context()
 
 
 
507
 
508
+ # 生成三种专业设计视图
509
+ design_views = ["正面设计图", "背面设计图", "侧面设计图"]
510
+ generated_designs = []
511
  design_choices = []
512
 
513
+ for i, view in enumerate(design_views):
514
  try:
515
+ progress(0.2 + i*0.25, desc=f"生成{view}...")
516
 
517
+ # 创建专业的设计提示词
518
+ design_prompt = create_professional_design_prompt(view, context, selected_suggestion)
 
 
 
 
 
519
 
520
+ # 使用SD模型生成设计
521
+ design_image = model_manager.generate_image(
522
+ prompt=design_prompt,
523
+ negative_prompt="person, face, model, background, blurry, low quality, text, watermark, realistic photo, 3d render",
524
+ num_inference_steps=30,
525
  width=512,
526
+ height=640,
527
+ guidance_scale=8.0
528
  )
529
 
530
+ generated_designs.append(design_image)
531
+ design_choices.append(f"{selected_suggestion} - {view}")
532
+ logger.info(f"成功生成{view}")
533
+
534
  except Exception as e:
535
+ logger.error(f"生成{view}失败: {e}")
536
  # 创建占位图像
537
+ placeholder = create_design_placeholder(view, 512, 640)
538
+ generated_designs.append(placeholder)
539
+ design_choices.append(f"{selected_suggestion} - {view} (占位)")
540
 
541
+ design_state.generated_designs = generated_designs
 
542
 
543
+ progress(1.0, desc="设计生成完成")
544
 
545
  return (
546
+ gr.Gallery(value=generated_designs, columns=3),
547
  gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
548
  )
549
 
550
  except Exception as e:
551
+ logger.error(f"专业设计生成失败: {e}")
552
  return gr.Gallery(value=[]), gr.Radio(choices=[])
553
 
554
+ def create_professional_design_prompt(view, context, suggestion):
555
+ """创建专业的服装设计提示词 - 避免token截断"""
556
+
557
+ # 关键词映射,避免中文token问题
558
+ style_keywords = {
559
+ "商务正装": "business formal suit professional",
560
+ "休闲风": "casual comfortable relaxed",
561
+ "运动风": "sportswear athletic active",
562
+ "时尚潮流": "fashion trendy modern stylish",
563
+ "复古风": "vintage retro classic",
564
+ "街头风": "streetwear urban hip",
565
+ "优雅风": "elegant sophisticated graceful"
566
+ }
567
+
568
+ color_keywords = {
569
+ "深红色": "deep red burgundy",
570
+ "橙红色": "orange red coral",
571
+ "金黄色": "golden yellow amber",
572
+ "草绿色": "grass green olive",
573
+ "翠绿色": "emerald green jade",
574
+ "天蓝色": "sky blue azure",
575
+ "宝蓝色": "royal blue navy",
576
+ "紫色": "purple violet",
577
+ "深黑色": "deep black charcoal",
578
+ "纯白色": "pure white ivory",
579
+ "深灰色": "dark gray slate"
580
+ }
581
+
582
+ fabric_keywords = {
583
+ "丝绸": "silk smooth luxurious",
584
+ "棉质": "cotton comfortable breathable",
585
+ "混纺": "blend modern synthetic",
586
+ "牛仔": "denim sturdy casual",
587
+ "毛呢": "wool warm textured"
588
+ }
589
+
590
+ view_keywords = {
591
+ "正面设计图": "front view technical drawing fashion flat",
592
+ "背面设计图": "back view technical drawing fashion flat",
593
+ "侧面设计图": "side view technical drawing fashion flat"
594
+ }
595
+
596
+ # 构建英文提示词
597
+ style_eng = style_keywords.get(context["main_style"], "modern fashion")
598
+ color_eng = color_keywords.get(context["dominant_colors"][0] if context["dominant_colors"] else "", "neutral colors")
599
+ fabric_eng = fabric_keywords.get(context["fabric_type"], "quality fabric")
600
+ view_eng = view_keywords.get(view, "technical fashion drawing")
601
+
602
+ # 专业服装设计提示词
603
+ prompt = (
604
+ f"{view_eng}, {style_eng} garment design, "
605
+ f"{color_eng} color scheme, {fabric_eng} material, "
606
+ f"clean fashion illustration, professional technical drawing, "
607
+ f"flat lay design, no model, clothing only, "
608
+ f"detailed stitching, precise proportions, "
609
+ f"fashion design sketch, minimalist background, "
610
+ f"high quality illustration, vector style"
611
+ )
612
+
613
+ logger.info(f"{view}设计提示词: {prompt}")
614
+ return prompt
615
+
616
+ def create_design_placeholder(view, width, height):
617
+ """创建设计占位图"""
618
+ img = Image.new('RGB', (width, height), color=(240, 240, 240))
619
+ draw = ImageDraw.Draw(img)
620
+
621
+ # 绘制基本轮廓
622
+ if "正面" in view:
623
+ # 画一个基本的衣服正面轮廓
624
+ draw.rectangle([width//4, height//6, 3*width//4, 5*height//6], outline=(100, 100, 100), width=3)
625
+ elif "背面" in view:
626
+ # 画一个基本的衣服背面轮廓
627
+ draw.rectangle([width//4, height//6, 3*width//4, 5*height//6], outline=(120, 120, 120), width=3)
628
+ else:
629
+ # 侧面轮廓
630
+ draw.ellipse([width//3, height//6, 2*width//3, 5*height//6], outline=(140, 140, 140), width=3)
631
+
632
+ # 添加文字
633
+ try:
634
+ font = ImageFont.load_default()
635
+ text = view
636
+ draw.text((width//2-50, height//2), text, fill=(80, 80, 80), font=font)
637
+ except:
638
+ pass
639
+
640
+ return img
641
+
642
+ def generate_3d_fitting_effect(selected_design_index, progress=gr.Progress()):
643
+ """生成专业3D试穿效果 - 标准模特展示"""
644
  try:
645
+ if not design_state.generated_designs or selected_design_index is None:
646
  return None
647
 
648
+ design_state.selected_design_index = selected_design_index
649
 
650
+ progress(0.1, desc="准备3D建模...")
 
 
651
 
652
+ # 获取设计上下文和选中的设计
653
+ context = design_state.get_design_context()
654
+ selected_design = design_state.generated_designs[selected_design_index]
655
+
656
+ progress(0.3, desc="构建3D试穿场景...")
657
+
658
+ # 创建专业3D试穿提示词
659
+ fitting_prompt = create_3d_fitting_prompt(context, selected_design_index)
660
 
661
+ progress(0.5, desc="AI 3D渲染中...")
662
 
 
663
  try:
664
+ # 使用ControlNet生成高质量3D试穿效果
665
+ fitting_image = model_manager.generate_controlnet_image(
666
+ image=design_state.original_image,
667
  prompt=fitting_prompt,
668
+ reference_image=selected_design,
669
+ negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed, bad anatomy, text, watermark, multiple people",
670
+ num_inference_steps=40,
671
  guidance_scale=8.5
672
  )
673
+
674
  progress(0.9, desc="完成3D渲染")
675
+ design_state.fitting_result = fitting_image
676
  logger.info("使用ControlNet生成3D试穿效果")
677
+ return fitting_image
678
+
679
  except Exception as e:
680
+ logger.warning(f"ControlNet 3D试穿失败: {e}")
681
+ # 回退到标准模型
682
+ progress(0.6, desc="使用标准模型生成...")
683
+ fitting_image = model_manager.generate_image(
 
 
684
  prompt=fitting_prompt,
685
+ negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed, bad anatomy, multiple people",
686
  num_inference_steps=35,
687
  width=512,
688
  height=768,
689
+ guidance_scale=8.0
690
  )
691
+
692
+ progress(0.9, desc="完成渲染")
693
+ design_state.fitting_result = fitting_image
694
+ return fitting_image
 
 
695
 
696
  except Exception as e:
697
+ logger.error(f"3D试穿生成失败: {e}")
698
+ return create_fitting_placeholder()
699
 
700
+ def create_3d_fitting_prompt(context, design_index):
701
+ """创建3D试穿提示词 - 英文避免token截断"""
702
+
703
+ # 风格关键词映射
704
+ style_keywords = {
705
+ "商务正装": "professional business attire formal suit",
706
+ "休闲风": "casual comfortable everyday wear",
707
+ "运动风": "athletic sportswear activewear",
708
+ "时尚潮流": "fashion forward trendy modern",
709
+ "复古风": "vintage retro classic style",
710
+ "街头风": "streetwear urban contemporary",
711
+ "优雅风": "elegant sophisticated refined"
712
+ }
713
+
714
+ color_keywords = {
715
+ "深红色": "deep red burgundy rich",
716
+ "橙红色": "coral orange warm",
717
+ "金黄色": "golden amber bright",
718
+ "草绿色": "olive green natural",
719
+ "翠绿色": "emerald jade vibrant",
720
+ "天蓝色": "sky blue light",
721
+ "宝蓝色": "royal navy deep",
722
+ "紫色": "purple violet",
723
+ "深黑色": "black charcoal dark",
724
+ "纯白色": "white clean pure",
725
+ "深灰色": "charcoal slate gray"
726
+ }
727
+
728
+ fabric_keywords = {
729
+ "丝绸": "silk luxurious smooth draping",
730
+ "棉质": "cotton comfortable natural texture",
731
+ "混纺": "modern blend synthetic comfort",
732
+ "牛仔": "denim sturdy casual texture",
733
+ "毛呢": "wool textured warm sophisticated"
734
+ }
735
+
736
+ # 获取英文关键词
737
+ style_eng = style_keywords.get(context["main_style"], "modern fashion")
738
+ color_eng = color_keywords.get(context["dominant_colors"][0] if context["dominant_colors"] else "", "neutral tones")
739
+ fabric_eng = fabric_keywords.get(context["fabric_type"], "quality fabric")
740
+
741
+ # 构建3D试穿提示词
742
+ prompt = (
743
+ f"professional 3D fashion model wearing {style_eng}, "
744
+ f"{color_eng} color scheme, {fabric_eng} material, "
745
+ f"full body pose, studio lighting, clean background, "
746
+ f"high quality 3D render, realistic fabric texture, "
747
+ f"perfect fit tailoring, fashion photography style, "
748
+ f"detailed clothing construction, professional modeling"
749
+ )
750
+
751
+ logger.info(f"3D试穿提示词: {prompt}")
752
+ return prompt
753
+
754
+ def create_fitting_placeholder():
755
+ """创建3D试穿占位图"""
756
+ img = Image.new('RGB', (512, 768), color=(245, 245, 245))
757
+ draw = ImageDraw.Draw(img)
758
+
759
+ # 画一个基本的人体轮廓
760
+ # 头部
761
+ draw.ellipse([206, 50, 306, 150], outline=(150, 150, 150), width=2)
762
+ # 身体
763
+ draw.rectangle([226, 150, 286, 400], outline=(150, 150, 150), width=2)
764
+ # 手臂
765
+ draw.rectangle([186, 170, 226, 350], outline=(150, 150, 150), width=2)
766
+ draw.rectangle([286, 170, 326, 350], outline=(150, 150, 150), width=2)
767
+ # 腿部
768
+ draw.rectangle([236, 400, 266, 650], outline=(150, 150, 150), width=2)
769
+ draw.rectangle([266, 400, 296, 650], outline=(150, 150, 150), width=2)
770
+
771
+ # 添加文字
772
  try:
773
+ font = ImageFont.load_default()
774
+ draw.text((200, 380), "3D Fitting", fill=(100, 100, 100), font=font)
775
+ except:
776
+ pass
777
+
778
+ return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
779
 
780
+ def export_design_report():
781
+ """导出完整的设计报告"""
782
+ if not design_state.original_image:
783
+ return "没有设计数据可导出"
784
+
785
  try:
786
+ context = design_state.get_design_context()
787
+
788
+ report = {
789
+ "设计项目报告": {
790
+ "生成时间": time.strftime("%Y-%m-%d %H:%M:%S"),
791
+ "项目概述": {
792
+ "设计描述": context["caption"],
793
+ "设计方向": context["design_direction"],
794
+ "主要风格": context["main_style"]
795
+ },
796
+ "色彩分析": {
797
+ "主色调": context["dominant_colors"],
798
+ "配色方案": design_state.color_analysis.get("color_harmony", ""),
799
+ "季节特征": design_state.color_analysis.get("season_analysis", ""),
800
+ "情感表达": design_state.color_analysis.get("color_palette", {}).get("颜色1", {}).get("emotion", "")
801
+ },
802
+ "材质分析": {
803
+ "面料类型": context["fabric_type"],
804
+ "质地特征": design_state.fabric_analysis.get("texture", ""),
805
+ "材质特性": design_state.fabric_analysis.get("fabric_properties", "")
806
+ },
807
+ "设计建议": {
808
+ "选择方向": design_state.design_direction,
809
+ "设计理念": f"基于{context['main_style']}风格,运用{context['dominant_colors'][0] if context['dominant_colors'] else '经典'}色调"
810
+ }
811
+ }
812
+ }
813
 
814
+ return json.dumps(report, ensure_ascii=False, indent=2)
 
815
 
816
  except Exception as e:
817
+ return f"报告生成失败: {str(e)}"
 
 
 
 
 
 
818
 
819
  def create_gradio_interface():
820
+ """创建改进的Gradio界面"""
821
 
822
+ with gr.Blocks(title="AI时尚设计师 Pro", theme="soft") as demo:
823
+ gr.Markdown("# 🎨 AI时尚设计师 Pro")
824
+ gr.Markdown("**专业AI驱动的服装设计平台** - 深度分析、智能设计、3D试穿")
825
 
826
  with gr.Row():
827
  with gr.Column(scale=1):
828
+ image_input = gr.Image(type="filepath", label="📸 上传服装参考图", height=400)
829
+ analyze_btn = gr.Button("🔍 AI深度分析", variant="primary", size="lg")
830
+
831
+ # 分析结果展示
832
+ with gr.Accordion("📊 详细分析报告", open=False):
833
+ analysis_output = gr.JSON(label="综合分析结果")
834
 
835
  with gr.Column(scale=2):
836
+ # 设计建议标签页
837
+ with gr.Tab("💡 智能设计建议"):
838
+ suggestions_output = gr.JSON(label="🎯 基于AI分析的个性化建议")
839
+ suggestion_choice = gr.Radio(label="🎨 选择设计方向", interactive=True)
840
+ generate_designs_btn = gr.Button("✨ 生成专业设计图", variant="primary", size="lg")
841
+
842
+ # 设计图标签页
843
+ with gr.Tab("👔 专业设计图"):
844
+ gr.Markdown("**服装设计三视图** - 正面/背面/侧面专业技术图")
845
+ designs_gallery = gr.Gallery(label="AI生成的专业设计图", columns=3, height=500)
846
+ design_choice = gr.Radio(label="🎯 选择设计方案", type="index", interactive=True)
847
+ generate_3d_btn = gr.Button("🎭 生成3D试穿效果", variant="primary", size="lg")
848
+
849
+ # 3D试穿标签页
850
+ with gr.Tab("🎭 3D虚拟试穿"):
851
+ gr.Markdown("**专业3D试穿展示** - 标准模特效果图")
852
+ fitting_result = gr.Image(label="3D虚拟试穿效果", height=600)
853
+
854
+ with gr.Row():
855
+ export_btn = gr.Button("📄 导出设计报告", variant="secondary")
856
+ reset_btn = gr.Button("🔄 重置项目", variant="secondary")
857
+
858
+ # 导出结果
859
+ with gr.Tab("📋 设计报告"):
860
+ report_output = gr.Textbox(label="完整设计报告", lines=20, max_lines=30)
861
+
862
+ # 系统控制面板
863
+ with gr.Accordion("🔧 系统控制面板", open=False):
864
+ with gr.Row():
865
+ cleanup_btn = gr.Button("🧹 清理显存", variant="secondary")
866
+ cpu_btn = gr.Button("💾 模型→CPU", variant="secondary")
867
+ gpu_btn = gr.Button("🚀 模型→GPU", variant="secondary")
868
+ reload_btn = gr.Button("🔄 重载模型", variant="primary")
869
 
870
+ gr.Markdown("""
871
+ **系统优化说明**:
872
+ - 🧹 清理显存:清理GPU缓存,不影响模型
873
+ - 💾 模型→CPU:释放GPU显存,推理速度会降低
874
+ - 🚀 模型→GPU:恢复GPU加速,提升生成速度
875
+ - 🔄 重载模型:强制重新加载所有AI模型
876
+ """)
877
+
878
+ # 事件绑定 - 完整工作流程
879
  analyze_btn.click(
880
+ fn=comprehensive_image_analysis,
881
  inputs=[image_input],
882
  outputs=[analysis_output, suggestions_output, suggestion_choice, designs_gallery]
883
  )
884
 
885
  generate_designs_btn.click(
886
+ fn=generate_professional_designs,
887
  inputs=[suggestion_choice],
888
  outputs=[designs_gallery, design_choice]
889
  )
890
 
891
  generate_3d_btn.click(
892
+ fn=generate_3d_fitting_effect,
893
  inputs=[design_choice],
894
  outputs=[fitting_result]
895
  )
896
 
897
+ export_btn.click(
898
+ fn=export_design_report,
899
  inputs=[],
900
+ outputs=[report_output]
901
  )
902
 
903
+ reset_btn.click(
904
+ fn=lambda: (design_state.reset(), {}, {}, gr.Radio(choices=[]), gr.Gallery(value=[]), None, ""),
905
  inputs=[],
906
+ outputs=[analysis_output, suggestions_output, suggestion_choice, designs_gallery, fitting_result, report_output]
907
  )
908
 
909
+ # 系统控制
910
+ cleanup_btn.click(fn=model_manager.cleanup, inputs=[], outputs=[])
911
+ cpu_btn.click(fn=model_manager.move_models_to_cpu, inputs=[], outputs=[])
912
+ gpu_btn.click(fn=model_manager.move_models_to_gpu, inputs=[], outputs=[])
913
+ reload_btn.click(fn=model_manager.force_reload_all_models, inputs=[], outputs=[])
 
 
 
 
 
 
914
 
915
+ # 使用指南
916
+ with gr.Accordion("📖 专业使用指南", open=False):
917
  gr.Markdown("""
918
+ ## 🚀 完整工作流程
 
 
 
 
919
 
920
+ ### 第一步:AI深度分析
921
+ 1. 上传高清服装参考图片
922
+ 2. 点击"AI深度分析"进行多维度智能分析
923
+ 3. 查看详细的风格、颜色、材质分析报告
924
+
925
+ ### 第二步:选择设计方向
926
+ 1. 在"智能设计建议"中查看个性化建议
927
+ 2. 基于AI分析结果选择最符合需求的设计方向
928
+ 3. 建议会整合风格、色彩、材质等所有分析维度
929
+
930
+ ### 第三步:生成专业设计
931
+ 1. 点击"生成专业设计图"获取三视图
932
+ 2. 包含正面、背面、侧面的专业技术图
933
+ 3. 所有设计都基于前期分析结果,确保一致性
934
+
935
+ ### 第四步:3D虚拟试穿
936
+ 1. 选择心仪的设计方案
937
+ 2. 生成标准模特的3D试穿效果
938
+ 3. 展示真实的着装效果和服装细节
939
+
940
+ ### 第五步:导出设计报告
941
+ 1. 获取完整的项目设计报告
942
+ 2. 包含所有分析数据和设计决策依据
943
+ 3. 支持进一步的设计开发和制作
944
+
945
+ ## 💡 专业建议
946
+ - **图片质量**:使用高分辨率、光线良好的服装图片
947
+ - **分析准确性**:让AI完整分析后再进行设计选择
948
+ - **设计连贯性**:所有生成内容都基于初始分析,确保风格统一
949
+ - **3D效果**:基于ControlNet技术,提供专业级试穿展示
950
  """)
951
 
952
  return demo
953
 
954
  if __name__ == "__main__":
 
955
  logger.info(f"Python版本: {sys.version}")
956
  logger.info(f"当前工作目录: {os.getcwd()}")
957
  logger.info(f"模型管理器状态: {'完整版' if MODELS_AVAILABLE else '简化版'}")
958
 
 
959
  demo = create_gradio_interface()
 
 
960
  demo.launch(
961
+ server_name="0.0.0.0",
962
  server_port=7860,
963
  share=False,
964
  show_error=True,
965
+ max_threads=4 # 增加线程数支持并发
966
  )