Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,100 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
def upload_and_analyze(image_path, progress=gr.Progress()):
|
| 4 |
-
"""完整的图片上传和分析流程 -
|
| 5 |
try:
|
| 6 |
# 重置应用状态
|
|
|
|
| 7 |
app_state = AppState()
|
| 8 |
|
| 9 |
if image_path is None:
|
|
@@ -13,12 +104,12 @@ def upload_and_analyze(image_path, progress=gr.Progress()):
|
|
| 13 |
image = Image.open(image_path).convert('RGB')
|
| 14 |
app_state.current_image = image
|
| 15 |
|
| 16 |
-
# 步骤1:
|
| 17 |
progress(0.2, desc="生成图像描述...")
|
| 18 |
try:
|
| 19 |
caption = model_manager.generate_caption(image)
|
| 20 |
app_state.current_caption = caption
|
| 21 |
-
logger.info(f"生成的图像描述: {caption}")
|
| 22 |
except Exception as e:
|
| 23 |
logger.error(f"生成描述失败: {e}")
|
| 24 |
caption = "时尚服装设计"
|
|
@@ -28,7 +119,7 @@ def upload_and_analyze(image_path, progress=gr.Progress()):
|
|
| 28 |
progress(0.4, desc="分析服装风格...")
|
| 29 |
try:
|
| 30 |
style_scores = model_manager.analyze_style(image)
|
| 31 |
-
logger.info(f"风格分析结果: {style_scores}")
|
| 32 |
except Exception as e:
|
| 33 |
logger.error(f"风格分析失败: {e}")
|
| 34 |
# 使用描述回退分析
|
|
@@ -37,12 +128,13 @@ def upload_and_analyze(image_path, progress=gr.Progress()):
|
|
| 37 |
# 步骤3: 提取颜色信息
|
| 38 |
progress(0.6, desc="提取颜色信息...")
|
| 39 |
colors = extract_dominant_colors(image)
|
|
|
|
| 40 |
|
| 41 |
-
# 步骤4: 整合分析结果
|
| 42 |
progress(0.8, desc="生成完整分析...")
|
| 43 |
app_state.current_analysis = {
|
| 44 |
"图像描述": caption,
|
| 45 |
-
"主要风格": max(style_scores
|
| 46 |
"风格评分": style_scores,
|
| 47 |
"主要颜色": colors,
|
| 48 |
"图像尺寸": f"{image.width} x {image.height}",
|
|
@@ -53,6 +145,7 @@ def upload_and_analyze(image_path, progress=gr.Progress()):
|
|
| 53 |
app_state.current_suggestions = generate_personalized_suggestions_v2(
|
| 54 |
caption, style_scores, colors
|
| 55 |
)
|
|
|
|
| 56 |
|
| 57 |
# 创建建议选项
|
| 58 |
choices = list(app_state.current_suggestions.keys())
|
|
@@ -67,11 +160,150 @@ def upload_and_analyze(image_path, progress=gr.Progress()):
|
|
| 67 |
)
|
| 68 |
|
| 69 |
except Exception as e:
|
| 70 |
-
logger.error(f"上传分析失败: {e}")
|
| 71 |
return {"错误": f"分析失败: {str(e)}"}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
def generate_designs(selected_suggestion, progress=gr.Progress()):
|
| 74 |
-
"""根据选择的建议使用SD模型生成设计
|
| 75 |
try:
|
| 76 |
if not selected_suggestion or not app_state.current_analysis:
|
| 77 |
return gr.Gallery(value=[]), gr.Radio(choices=[])
|
|
@@ -137,16 +369,16 @@ def generate_designs(selected_suggestion, progress=gr.Progress()):
|
|
| 137 |
return gr.Gallery(value=[]), gr.Radio(choices=[])
|
| 138 |
|
| 139 |
def generate_3d_fitting(selected_design_index, progress=gr.Progress()):
|
| 140 |
-
"""生成3D试穿效果 -
|
| 141 |
try:
|
| 142 |
-
if not app_state.design_images or not app_state.current_image:
|
| 143 |
return None
|
| 144 |
|
| 145 |
progress(0.1, desc="准备3D试穿...")
|
| 146 |
|
| 147 |
# 获取选中的设计
|
| 148 |
selected_image = app_state.design_images[selected_design_index]
|
| 149 |
-
app_state.
|
| 150 |
|
| 151 |
# 基于原始图像和选择的设计创建3D试穿提示词
|
| 152 |
fitting_prompt = create_3d_fitting_prompt(
|
|
@@ -156,30 +388,30 @@ def generate_3d_fitting(selected_design_index, progress=gr.Progress()):
|
|
| 156 |
|
| 157 |
progress(0.3, desc="生成3D模型...")
|
| 158 |
|
| 159 |
-
#
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
image
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
|
| 176 |
-
#
|
| 177 |
progress(0.5, desc="使用标准模型生成...")
|
| 178 |
try:
|
| 179 |
image = model_manager.generate_image(
|
| 180 |
prompt=fitting_prompt,
|
| 181 |
negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed, bad anatomy",
|
| 182 |
-
num_inference_steps=
|
| 183 |
width=512,
|
| 184 |
height=768,
|
| 185 |
guidance_scale=7.5
|
|
@@ -260,7 +492,7 @@ def create_3d_fitting_prompt(design_index, analysis):
|
|
| 260 |
design_desc = f"设计方案 {design_index+1}"
|
| 261 |
|
| 262 |
# 3D试穿基础提示词
|
| 263 |
-
base_prompt = "3D虚拟试穿,真实人体模特穿着"
|
| 264 |
|
| 265 |
# 添加风格和颜色信息
|
| 266 |
style_desc = f"{style_info}风格服装"
|
|
@@ -270,7 +502,7 @@ def create_3d_fitting_prompt(design_index, analysis):
|
|
| 270 |
full_prompt = (
|
| 271 |
f"{base_prompt} {style_desc},{color_desc}。"
|
| 272 |
f"全身展示,专业工作室灯光,高质量3D渲染,"
|
| 273 |
-
f"
|
| 274 |
f"设计灵感:'{caption}'。"
|
| 275 |
f"具体设计:{design_desc}"
|
| 276 |
)
|
|
@@ -280,11 +512,104 @@ def create_3d_fitting_prompt(design_index, analysis):
|
|
| 280 |
|
| 281 |
except Exception as e:
|
| 282 |
logger.error(f"创建3D提示词失败: {e}")
|
| 283 |
-
return "3D虚拟时尚试穿,真实人体模特,全身展示,工作室灯光"
|
| 284 |
|
| 285 |
def create_placeholder_image(width, height):
|
| 286 |
"""创建占位图像"""
|
| 287 |
-
color = (random.randint(120, 200), random.randint(120, 200), random.randint(120, 200)
|
| 288 |
return Image.new('RGB', (width, height), color=color)
|
| 289 |
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
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'
|
| 14 |
+
os.environ['MKL_NUM_THREADS'] = '1'
|
| 15 |
+
|
| 16 |
+
# 抑制警告
|
| 17 |
+
warnings.filterwarnings("ignore")
|
| 18 |
+
|
| 19 |
+
# 设置日志
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
# 检查模型管理器是否存在
|
| 24 |
+
try:
|
| 25 |
+
from models.model_manager import ModelManager
|
| 26 |
+
MODELS_AVAILABLE = True
|
| 27 |
+
logger.info("模型管理器导入成功")
|
| 28 |
+
except ImportError as e:
|
| 29 |
+
logger.warning(f"模型管理器导入失败: {e}")
|
| 30 |
+
logger.info("将使用简化版本运行")
|
| 31 |
+
MODELS_AVAILABLE = False
|
| 32 |
+
ModelManager = None
|
| 33 |
+
|
| 34 |
+
class SimpleModelManager:
|
| 35 |
+
"""简化的模型管理器,用于演示模式"""
|
| 36 |
+
def __init__(self):
|
| 37 |
+
self.device = "cpu"
|
| 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):
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
# 全局状态管理
|
| 70 |
+
class AppState:
|
| 71 |
+
def __init__(self):
|
| 72 |
+
self.current_image = None
|
| 73 |
+
self.current_caption = ""
|
| 74 |
+
self.current_analysis = {}
|
| 75 |
+
self.current_suggestions = {}
|
| 76 |
+
self.design_images = []
|
| 77 |
+
self.selected_suggestion = ""
|
| 78 |
+
self.selected_design_index = -1
|
| 79 |
+
|
| 80 |
+
# 初始化模型管理器
|
| 81 |
+
if MODELS_AVAILABLE:
|
| 82 |
+
try:
|
| 83 |
+
model_manager = ModelManager()
|
| 84 |
+
logger.info("使用完整模型管理器")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
logger.error(f"初始化完整模型管理器失败: {e}")
|
| 87 |
+
model_manager = SimpleModelManager()
|
| 88 |
+
else:
|
| 89 |
+
model_manager = SimpleModelManager()
|
| 90 |
+
|
| 91 |
+
app_state = AppState()
|
| 92 |
|
| 93 |
def upload_and_analyze(image_path, progress=gr.Progress()):
|
| 94 |
+
"""完整的图片上传和分析流程 - 使用真实模型分析"""
|
| 95 |
try:
|
| 96 |
# 重置应用状态
|
| 97 |
+
global app_state
|
| 98 |
app_state = AppState()
|
| 99 |
|
| 100 |
if image_path is None:
|
|
|
|
| 104 |
image = Image.open(image_path).convert('RGB')
|
| 105 |
app_state.current_image = image
|
| 106 |
|
| 107 |
+
# 步骤1: 使用BLIP模型生成图像描述
|
| 108 |
progress(0.2, desc="生成图像描述...")
|
| 109 |
try:
|
| 110 |
caption = model_manager.generate_caption(image)
|
| 111 |
app_state.current_caption = caption
|
| 112 |
+
logger.info(f"BLIP生成的图像描述: {caption}")
|
| 113 |
except Exception as e:
|
| 114 |
logger.error(f"生成描述失败: {e}")
|
| 115 |
caption = "时尚服装设计"
|
|
|
|
| 119 |
progress(0.4, desc="分析服装风格...")
|
| 120 |
try:
|
| 121 |
style_scores = model_manager.analyze_style(image)
|
| 122 |
+
logger.info(f"CLIP风格分析结果: {style_scores}")
|
| 123 |
except Exception as e:
|
| 124 |
logger.error(f"风格分析失败: {e}")
|
| 125 |
# 使用描述回退分析
|
|
|
|
| 128 |
# 步骤3: 提取颜色信息
|
| 129 |
progress(0.6, desc="提取颜色信息...")
|
| 130 |
colors = extract_dominant_colors(image)
|
| 131 |
+
logger.info(f"提取的主要颜色: {colors}")
|
| 132 |
|
| 133 |
+
# 步骤4: 整合分析结果
|
| 134 |
progress(0.8, desc="生成完整分析...")
|
| 135 |
app_state.current_analysis = {
|
| 136 |
"图像描述": caption,
|
| 137 |
+
"主要风格": max(style_scores, key=style_scores.get),
|
| 138 |
"风格评分": style_scores,
|
| 139 |
"主要颜色": colors,
|
| 140 |
"图像尺寸": f"{image.width} x {image.height}",
|
|
|
|
| 145 |
app_state.current_suggestions = generate_personalized_suggestions_v2(
|
| 146 |
caption, style_scores, colors
|
| 147 |
)
|
| 148 |
+
logger.info(f"生成的设计建议: {app_state.current_suggestions}")
|
| 149 |
|
| 150 |
# 创建建议选项
|
| 151 |
choices = list(app_state.current_suggestions.keys())
|
|
|
|
| 160 |
)
|
| 161 |
|
| 162 |
except Exception as e:
|
| 163 |
+
logger.error(f"上传分析失败: {e}", exc_info=True)
|
| 164 |
return {"错误": f"分析失败: {str(e)}"}, {}, gr.Radio(choices=[]), gr.Gallery(value=[])
|
| 165 |
|
| 166 |
+
def analyze_style_from_caption(caption):
|
| 167 |
+
"""基于描述分析风格(回退方案)"""
|
| 168 |
+
caption_lower = caption.lower()
|
| 169 |
+
|
| 170 |
+
style_keywords = {
|
| 171 |
+
"商务正装": ["suit", "formal", "business", "office", "professional", "tie", "blazer", "西装", "正装", "商务"],
|
| 172 |
+
"休闲风": ["casual", "relaxed", "comfortable", "everyday", "jeans", "t-shirt", "休闲", "日常"],
|
| 173 |
+
"运动风": ["sport", "athletic", "gym", "fitness", "running", "training", "运动", "健身"],
|
| 174 |
+
"时尚潮流": ["fashion", "trendy", "stylish", "modern", "chic", "designer", "时尚", "潮流"],
|
| 175 |
+
"复古风": ["vintage", "retro", "classic", "traditional", "old-fashioned", "复古", "经典"],
|
| 176 |
+
"街头风": ["street", "urban", "hip-hop", "cool", "edgy", "街头", "嘻哈"],
|
| 177 |
+
"优雅风": ["elegant", "sophisticated", "graceful", "refined", "classy", "优雅", "高贵"]
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
style_scores = {}
|
| 181 |
+
for style, keywords in style_keywords.items():
|
| 182 |
+
score = sum(0.2 for keyword in keywords if keyword in caption_lower)
|
| 183 |
+
if score > 0:
|
| 184 |
+
style_scores[style] = min(score, 1.0)
|
| 185 |
+
|
| 186 |
+
# 如果没有匹配,给默认评分
|
| 187 |
+
if not style_scores:
|
| 188 |
+
style_scores = {"休闲风": 0.7, "时尚潮流": 0.5}
|
| 189 |
+
|
| 190 |
+
return style_scores
|
| 191 |
+
|
| 192 |
+
def extract_dominant_colors(image):
|
| 193 |
+
"""提取图像主要颜色 - 真实算法"""
|
| 194 |
+
try:
|
| 195 |
+
from sklearn.cluster import KMeans
|
| 196 |
+
|
| 197 |
+
# 调整图像大小以提高处理速度
|
| 198 |
+
image = image.resize((150, 150))
|
| 199 |
+
|
| 200 |
+
# 转换为numpy数组
|
| 201 |
+
img_array = np.array(image)
|
| 202 |
+
pixels = img_array.reshape(-1, 3)
|
| 203 |
+
|
| 204 |
+
# 使用KMeans聚类找到主要颜色
|
| 205 |
+
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
|
| 206 |
+
kmeans.fit(pixels)
|
| 207 |
+
|
| 208 |
+
# 获取主要颜色
|
| 209 |
+
colors = []
|
| 210 |
+
for color in kmeans.cluster_centers_:
|
| 211 |
+
color_name = rgb_to_color_name(color)
|
| 212 |
+
colors.append(color_name)
|
| 213 |
+
|
| 214 |
+
return colors
|
| 215 |
+
except Exception as e:
|
| 216 |
+
logger.error(f"颜色提取失败: {e}")
|
| 217 |
+
return ["主色调", "辅助色", "点缀色"]
|
| 218 |
+
|
| 219 |
+
def rgb_to_color_name(rgb):
|
| 220 |
+
"""将RGB值转换为颜色名称 - 真实算法"""
|
| 221 |
+
try:
|
| 222 |
+
r, g, b = rgb.astype(int)
|
| 223 |
+
|
| 224 |
+
if r > 200 and g > 200 and b > 200:
|
| 225 |
+
return "白色系"
|
| 226 |
+
elif r < 50 and g < 50 and b < 50:
|
| 227 |
+
return "黑色系"
|
| 228 |
+
elif r > g and r > b:
|
| 229 |
+
return "红色系" if r > 150 else "深红色系"
|
| 230 |
+
elif g > r and g > b:
|
| 231 |
+
return "绿色系" if g > 150 else "深绿色系"
|
| 232 |
+
elif b > r and b > g:
|
| 233 |
+
return "蓝色系" if b > 150 else "深蓝色系"
|
| 234 |
+
elif r > 150 and g > 150:
|
| 235 |
+
return "黄色系"
|
| 236 |
+
elif r > 100 and b > 100:
|
| 237 |
+
return "紫色系"
|
| 238 |
+
elif g > 100 and b > 100:
|
| 239 |
+
return "青色系"
|
| 240 |
+
else:
|
| 241 |
+
return "灰色系"
|
| 242 |
+
except:
|
| 243 |
+
return "混合色调"
|
| 244 |
+
|
| 245 |
+
def generate_personalized_suggestions_v2(caption, style_scores, colors):
|
| 246 |
+
"""基于模型分析结果生成个性化建议"""
|
| 247 |
+
try:
|
| 248 |
+
# 获取主要风格
|
| 249 |
+
main_style = max(style_scores.keys(), key=style_scores.get) if style_scores else "时尚潮流"
|
| 250 |
+
main_color = colors[0] if colors else "经典色"
|
| 251 |
+
|
| 252 |
+
# 基于主要风格和颜色生成建议
|
| 253 |
+
suggestions = {}
|
| 254 |
+
|
| 255 |
+
if "商务" in main_style:
|
| 256 |
+
suggestions = {
|
| 257 |
+
f"经典{main_style}": f"保持{main_style}特色,强调{main_color}的专业感",
|
| 258 |
+
f"现代{main_style}": f"在{main_style}基础上融入现代设计元素",
|
| 259 |
+
f"时尚{main_style}": f"{main_style}结合当下流行趋势",
|
| 260 |
+
f"个性{main_style}": f"基于{main_color}打造独特的{main_style}风格"
|
| 261 |
+
}
|
| 262 |
+
elif "休闲" in main_style:
|
| 263 |
+
suggestions = {
|
| 264 |
+
"舒适休闲": f"强化舒适感,突出{main_color}的自然魅力",
|
| 265 |
+
"时尚休闲": f"休闲风格融入时尚元素",
|
| 266 |
+
"运动休闲": f"结合运动风格的休闲设计",
|
| 267 |
+
"优雅休闲": f"提升休闲装的优雅度"
|
| 268 |
+
}
|
| 269 |
+
elif "运动" in main_style:
|
| 270 |
+
suggestions = {
|
| 271 |
+
"专业运动": f"强化功能性,突出{main_color}的活力",
|
| 272 |
+
"时尚运动": f"运动风格加入潮流设计",
|
| 273 |
+
"休闲运动": f"适合日常的运动休闲风",
|
| 274 |
+
"户外运动": f"适应户外环境的运动设计"
|
| 275 |
+
}
|
| 276 |
+
else:
|
| 277 |
+
# 其他风格的通用建议
|
| 278 |
+
suggestions = {
|
| 279 |
+
f"经典{main_style}": f"保持{main_style}的经典特色",
|
| 280 |
+
f"现代{main_style}": f"{main_style}融入现代设计理念",
|
| 281 |
+
f"创新{main_style}": f"在{main_style}基础上的创新尝试",
|
| 282 |
+
f"个性{main_style}": f"基于{main_color}的个性化{main_style}"
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
# 添加基于颜色的额外建议
|
| 286 |
+
color_suggestions = {
|
| 287 |
+
f"单色系设计": f"围绕{main_color}打造单色系搭配",
|
| 288 |
+
f"撞色搭配": f"以{main_color}为主的撞色设计"
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
# 合并建议(限制数量避免选项过多)
|
| 292 |
+
final_suggestions = dict(list(suggestions.items())[:4] + list(color_suggestions.items())[:2])
|
| 293 |
+
|
| 294 |
+
return final_suggestions
|
| 295 |
+
|
| 296 |
+
except Exception as e:
|
| 297 |
+
logger.error(f"生成建议失败: {e}")
|
| 298 |
+
return {
|
| 299 |
+
"经典设计": "传统经典的设计风格",
|
| 300 |
+
"现代风格": "融入现代设计元素",
|
| 301 |
+
"时尚潮流": "跟随当下时尚趋势",
|
| 302 |
+
"个性化": "独特的个性化设计"
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
def generate_designs(selected_suggestion, progress=gr.Progress()):
|
| 306 |
+
"""根据选择的建议使用SD模型生成设计"""
|
| 307 |
try:
|
| 308 |
if not selected_suggestion or not app_state.current_analysis:
|
| 309 |
return gr.Gallery(value=[]), gr.Radio(choices=[])
|
|
|
|
| 369 |
return gr.Gallery(value=[]), gr.Radio(choices=[])
|
| 370 |
|
| 371 |
def generate_3d_fitting(selected_design_index, progress=gr.Progress()):
|
| 372 |
+
"""生成3D试穿效果 - 使用更精细的模型"""
|
| 373 |
try:
|
| 374 |
+
if not app_state.design_images or not app_state.current_image or selected_design_index is None:
|
| 375 |
return None
|
| 376 |
|
| 377 |
progress(0.1, desc="准备3D试穿...")
|
| 378 |
|
| 379 |
# 获取选中的设计
|
| 380 |
selected_image = app_state.design_images[selected_design_index]
|
| 381 |
+
app_state.selected_design_index = selected_design_index
|
| 382 |
|
| 383 |
# 基于原始图像和选择的设计创建3D试穿提示词
|
| 384 |
fitting_prompt = create_3d_fitting_prompt(
|
|
|
|
| 388 |
|
| 389 |
progress(0.3, desc="生成3D模型...")
|
| 390 |
|
| 391 |
+
# 使用更精细的3D模型
|
| 392 |
+
try:
|
| 393 |
+
# 使用专门的3D试穿模型
|
| 394 |
+
image = model_manager.generate_controlnet_image(
|
| 395 |
+
image=app_state.current_image, # 使用原始图像作为控制
|
| 396 |
+
prompt=fitting_prompt,
|
| 397 |
+
reference_image=selected_image, # 设计风格参考
|
| 398 |
+
negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed",
|
| 399 |
+
num_inference_steps=40, # 更多步骤以获得更高质量
|
| 400 |
+
guidance_scale=8.5
|
| 401 |
+
)
|
| 402 |
+
progress(0.9, desc="完成3D渲染")
|
| 403 |
+
logger.info("使用ControlNet生成3D试穿效果")
|
| 404 |
+
return image
|
| 405 |
+
except Exception as e:
|
| 406 |
+
logger.warning(f"3D模型生成失败: {e}")
|
| 407 |
|
| 408 |
+
# 回退到普通模型
|
| 409 |
progress(0.5, desc="使用标准模型生成...")
|
| 410 |
try:
|
| 411 |
image = model_manager.generate_image(
|
| 412 |
prompt=fitting_prompt,
|
| 413 |
negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs, deformed, bad anatomy",
|
| 414 |
+
num_inference_steps=35,
|
| 415 |
width=512,
|
| 416 |
height=768,
|
| 417 |
guidance_scale=7.5
|
|
|
|
| 492 |
design_desc = f"设计方案 {design_index+1}"
|
| 493 |
|
| 494 |
# 3D试穿基础提示词
|
| 495 |
+
base_prompt = "高精度3D虚拟试穿,真实人体模特穿着"
|
| 496 |
|
| 497 |
# 添加风格和颜色信息
|
| 498 |
style_desc = f"{style_info}风格服装"
|
|
|
|
| 502 |
full_prompt = (
|
| 503 |
f"{base_prompt} {style_desc},{color_desc}。"
|
| 504 |
f"全身展示,专业工作室灯光,高质量3D渲染,"
|
| 505 |
+
f"真实面料质感,合身剪裁,高清细节。"
|
| 506 |
f"设计灵感:'{caption}'。"
|
| 507 |
f"具体设计:{design_desc}"
|
| 508 |
)
|
|
|
|
| 512 |
|
| 513 |
except Exception as e:
|
| 514 |
logger.error(f"创建3D提示词失败: {e}")
|
| 515 |
+
return "高精度3D虚拟时尚试穿,真实人体模特,全身展示,工作室灯光"
|
| 516 |
|
| 517 |
def create_placeholder_image(width, height):
|
| 518 |
"""创建占位图像"""
|
| 519 |
+
color = (random.randint(120, 200), random.randint(120, 200), random.randint(120, 200)
|
| 520 |
return Image.new('RGB', (width, height), color=color)
|
| 521 |
|
| 522 |
+
def create_gradio_interface():
|
| 523 |
+
"""创建Gradio用户界面"""
|
| 524 |
+
|
| 525 |
+
with gr.Blocks(title="AI时尚设计师", theme="soft") as demo:
|
| 526 |
+
gr.Markdown("# 🎨 AI时尚设计师")
|
| 527 |
+
gr.Markdown("上传服装图片,AI将分析风格并生成个性化设计方案和3D试穿效果")
|
| 528 |
+
|
| 529 |
+
with gr.Row():
|
| 530 |
+
with gr.Column(scale=1):
|
| 531 |
+
image_input = gr.Image(type="filepath", label="上传参考图片", height=400)
|
| 532 |
+
analyze_btn = gr.Button("🔍 AI智能分析", variant="primary", size="lg")
|
| 533 |
+
|
| 534 |
+
with gr.Column(scale=2):
|
| 535 |
+
analysis_output = gr.JSON(label="🎯 AI分析结果")
|
| 536 |
+
|
| 537 |
+
with gr.Tab("💡 设计建议"):
|
| 538 |
+
suggestions_output = gr.JSON(label="个性化设计建议")
|
| 539 |
+
suggestion_choice = gr.Radio(label="选择设计方向", interactive=True)
|
| 540 |
+
generate_designs_btn = gr.Button("🎨 生成设计方案", variant="primary")
|
| 541 |
+
|
| 542 |
+
with gr.Tab("👔 样衣设计"):
|
| 543 |
+
designs_gallery = gr.Gallery(label="AI生成的设计方案", columns=3, height=400)
|
| 544 |
+
design_choice = gr.Radio(label="选择设计方案", type="index", interactive=True)
|
| 545 |
+
generate_3d_btn = gr.Button("🎭 生成3D试穿效果", variant="primary")
|
| 546 |
+
|
| 547 |
+
with gr.Tab("👤 3D试穿效果"):
|
| 548 |
+
fitting_result = gr.Image(label="3D试穿效果", height=600)
|
| 549 |
+
|
| 550 |
+
# 系统状态和控制
|
| 551 |
+
with gr.Row():
|
| 552 |
+
with gr.Column():
|
| 553 |
+
gr.Markdown("### 🔧 系统控制")
|
| 554 |
+
cleanup_btn = gr.Button("🧹 清理内存", variant="secondary")
|
| 555 |
+
gr.Markdown("> **提示**: 如果遇到内存问题,请点击清理内存按钮")
|
| 556 |
+
|
| 557 |
+
# 事件绑定 - 完整的流水线连接
|
| 558 |
+
analyze_btn.click(
|
| 559 |
+
fn=upload_and_analyze,
|
| 560 |
+
inputs=[image_input],
|
| 561 |
+
outputs=[analysis_output, suggestions_output, suggestion_choice, designs_gallery]
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
generate_designs_btn.click(
|
| 565 |
+
fn=generate_designs,
|
| 566 |
+
inputs=[suggestion_choice],
|
| 567 |
+
outputs=[designs_gallery, design_choice]
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
generate_3d_btn.click(
|
| 571 |
+
fn=generate_3d_fitting,
|
| 572 |
+
inputs=[design_choice],
|
| 573 |
+
outputs=[fitting_result]
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
cleanup_btn.click(
|
| 577 |
+
fn=model_manager.cleanup,
|
| 578 |
+
inputs=[],
|
| 579 |
+
outputs=[]
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
# 添加使用说明
|
| 583 |
+
with gr.Row():
|
| 584 |
+
gr.Markdown("""
|
| 585 |
+
### 📋 使用流程:
|
| 586 |
+
1. **上传图片** → 点击"AI智能分析"进行风格识别
|
| 587 |
+
2. **查看建议** → 在"设计建议"标签中选择心仪的设计方向
|
| 588 |
+
3. **生成设计** → 点击"生成设计方案"查看AI设计的服装
|
| 589 |
+
4. **3D试穿** → 选择喜欢的设计,点击"生成3D试穿效果"
|
| 590 |
+
|
| 591 |
+
💡 **提示**:
|
| 592 |
+
- 每一步都会调用相应的AI模型,请耐心等待生成完成
|
| 593 |
+
- 使用ControlNet模型生成高质量的3D试穿效果
|
| 594 |
+
- 所有设计都基于原始图片的分析结果
|
| 595 |
+
""")
|
| 596 |
+
|
| 597 |
+
return demo
|
| 598 |
+
|
| 599 |
+
if __name__ == "__main__":
|
| 600 |
+
# 检查环境
|
| 601 |
+
logger.info(f"Python版本: {sys.version}")
|
| 602 |
+
logger.info(f"当前工作目录: {os.getcwd()}")
|
| 603 |
+
logger.info(f"模型管理器状态: {'完整版' if MODELS_AVAILABLE else '简化版'}")
|
| 604 |
+
|
| 605 |
+
# 创建并启动界面
|
| 606 |
+
demo = create_gradio_interface()
|
| 607 |
+
|
| 608 |
+
# 启动应用
|
| 609 |
+
demo.launch(
|
| 610 |
+
server_name="0.0.0.0",
|
| 611 |
+
server_port=7860,
|
| 612 |
+
share=False,
|
| 613 |
+
show_error=True,
|
| 614 |
+
max_threads=2
|
| 615 |
+
)
|