Humphreykowl commited on
Commit
e6de78f
·
verified ·
1 Parent(s): 6f9c5be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -821
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import sys
3
  import logging
@@ -21,9 +22,9 @@ warnings.filterwarnings("ignore")
21
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
22
  logger = logging.getLogger(__name__)
23
 
24
- # 检查模型管理器是否存在
25
  try:
26
- from models.model_manager import ModelManager
27
  MODELS_AVAILABLE = True
28
  logger.info("模型管理器导入成功")
29
  except ImportError as e:
@@ -53,9 +54,15 @@ class SimpleModelManager:
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):
@@ -84,8 +91,10 @@ class DesignState:
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
  """获取完整的设计上下文,用于生成连贯的设计"""
@@ -146,821 +155,4 @@ def advanced_color_analysis(image):
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
- )
 
1
+ # app.py — 可直接替换你原项目中的文件
2
  import os
3
  import sys
4
  import logging
 
22
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
23
  logger = logging.getLogger(__name__)
24
 
25
+ # 检查模型管理器是否存在(注意:路径已调整为你指定的 model/modal_manager.py)
26
  try:
27
+ from model.modal_manager import ModelManager
28
  MODELS_AVAILABLE = True
29
  logger.info("模型管理器导入成功")
30
  except ImportError as e:
 
54
  width = kwargs.get('width', 512)
55
  height = kwargs.get('height', 512)
56
  img = Image.new('RGB', (width, height), color=(200, 200, 200))
57
+ draw = ImageDraw.Draw(img)
58
+ try:
59
+ font = ImageFont.load_default()
60
+ draw.text((8, 8), prompt[:240], fill=(10,10,10), font=font)
61
+ except Exception:
62
+ pass
63
  return img
64
 
65
+ def generate_controlnet_image(self, image, prompt, reference_image=None, **kwargs):
66
  return self.generate_image(prompt, width=512, height=768)
67
 
68
  def cleanup(self):
 
91
  self.design_direction = ""
92
  self.design_concepts = []
93
  self.generated_designs = []
94
+ self.generated_design_seeds = []
95
  self.selected_design_index = -1
96
  self.fitting_result = None
97
+ self.fitting_multiview = []
98
 
99
  def get_design_context(self):
100
  """获取完整的设计上下文,用于生成连贯的设计"""
 
155
 
156
  for i, (color, percentage) in enumerate(color_data):
157
  color_name = rgb_to_detailed_color_name(color)
158
+ color_emotion =_