Humphreykowl commited on
Commit
990379b
·
verified ·
1 Parent(s): df5cbad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +307 -54
app.py CHANGED
@@ -1,11 +1,15 @@
1
  # app.py (Gradio界面)
2
  import gradio as gr
3
- from main import app
4
  import requests
5
  from PIL import Image
6
- import json
 
 
 
 
 
7
 
8
- # 导入模型管理器
9
  from models.model_manager import ModelManager
10
 
11
  # 初始化模型管理器
@@ -18,27 +22,16 @@ def upload_and_analyze(image_path):
18
  return {}, {}, []
19
 
20
  # 打开图片
21
- image = Image.open(image_path)
22
 
23
  # 生成图像描述
24
  caption = model_manager.generate_caption(image)
25
 
26
- # 模拟风格分析结果
27
- analysis_result = {
28
- "图像描述": caption,
29
- "检测到的颜色": ["蓝色", "白色", "黑色"],
30
- "风格类型": "休闲风",
31
- "服装类别": "上衣",
32
- "适合场景": ["日常", "休闲", "约会"]
33
- }
34
 
35
- # 生成设计建议
36
- suggestions = {
37
- "建议1": "现代简约风格搭配",
38
- "建议2": "复古经典款式",
39
- "建议3": "运动休闲风格",
40
- "建议4": "商务正装风格"
41
- }
42
 
43
  # 创建选择选项
44
  choices = list(suggestions.keys())
@@ -49,18 +42,207 @@ def upload_and_analyze(image_path):
49
  error_result = {"错误": f"分析失败: {str(e)}"}
50
  return error_result, {}, []
51
 
52
- def generate_designs(selected_suggestion):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  """根据选择的建议生成设计"""
54
  try:
55
  if not selected_suggestion:
56
  return [], gr.Radio(choices=[])
57
 
 
 
58
  # 生成设计图像的提示词
59
  design_prompts = {
60
- "建议1": "modern minimalist clothing design, clean lines, neutral colors",
61
- "建议2": "vintage classic fashion design, retro style, elegant",
62
- "建议3": "sporty casual wear design, comfortable, athletic",
63
- "建议4": "business formal attire, professional, sophisticated"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
 
66
  prompt = design_prompts.get(selected_suggestion, "fashion design, stylish clothing")
@@ -71,44 +253,75 @@ def generate_designs(selected_suggestion):
71
 
72
  for i in range(3): # 生成3个设计
73
  try:
 
 
 
74
  image = model_manager.generate_image(
75
- prompt=f"{prompt}, design {i+1}",
76
- negative_prompt="blurry, low quality, distorted",
77
- num_inference_steps=20
78
  )
 
79
  if image:
80
  design_images.append(image)
81
- design_choices.append(f"设计方案 {i+1}")
82
  except Exception as e:
83
  print(f"生成设计 {i+1} 失败: {e}")
 
 
 
 
 
 
 
 
84
 
85
- # 如果没有生成图像,返回空结果
86
- if not design_images:
87
- return [], gr.Radio(choices=[])
88
-
89
  return design_images, gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
90
 
91
  except Exception as e:
92
  print(f"设计生成错误: {e}")
93
  return [], gr.Radio(choices=[])
94
 
95
- def generate_3d_fitting(selected_design):
96
  """生成3D试穿效果"""
97
  try:
98
  if not selected_design:
99
  return None
100
 
 
 
101
  # 生成3D试穿效果的提示词
102
- fitting_prompt = f"3D fashion fitting, virtual try-on, {selected_design}, realistic human model"
 
 
103
 
104
  # 使用模型生成3D试穿图像
105
- fitting_image = model_manager.generate_image(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  prompt=fitting_prompt,
107
- negative_prompt="blurry, distorted, low quality, unrealistic",
108
- num_inference_steps=25
109
  )
110
 
111
- return fitting_image
 
112
 
113
  except Exception as e:
114
  print(f"3D试穿生成错误: {e}")
@@ -117,27 +330,45 @@ def generate_3d_fitting(selected_design):
117
  def create_gradio_interface():
118
  """创建Gradio用户界面"""
119
 
120
- with gr.Blocks(title="AI时尚设计师") as demo:
121
  gr.Markdown("# 🎨 AI时尚设计师")
122
  gr.Markdown("上传图片,获得专业的服装设计建议和3D试穿效果")
123
 
124
- with gr.Tab("1. 图片上传与分析"):
125
- image_input = gr.Image(type="filepath", label="上传参考图片")
126
- analyze_btn = gr.Button("分析风格")
127
- analysis_output = gr.JSON(label="风格分析结果")
 
 
 
 
 
 
 
 
128
 
129
- with gr.Tab("2. 设计建议"):
130
- suggestions_output = gr.JSON(label="设计建议")
131
- suggestion_choice = gr.Radio(label="选择设计建议")
132
- generate_designs_btn = gr.Button("生成样衣设计")
133
 
134
- with gr.Tab("3. 样衣设计"):
135
- designs_gallery = gr.Gallery(label="样衣设计图")
136
- design_choice = gr.Radio(label="选择设计")
137
- generate_3d_btn = gr.Button("生成3D试穿")
138
 
139
- with gr.Tab("4. 3D试穿"):
140
- fitting_result = gr.Image(label="3D试穿效果")
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  # 事件绑定
143
  analyze_btn.click(
@@ -157,9 +388,31 @@ def create_gradio_interface():
157
  inputs=[design_choice],
158
  outputs=[fitting_result]
159
  )
 
 
 
 
 
 
 
 
 
160
 
161
  return demo
162
 
163
  if __name__ == "__main__":
 
 
 
 
 
 
 
164
  demo = create_gradio_interface()
165
- demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
 
 
 
 
 
 
 
1
  # app.py (Gradio界面)
2
  import gradio as gr
 
3
  import requests
4
  from PIL import Image
5
+ import numpy as np
6
+ from sklearn.cluster import KMeans
7
+ import time
8
+ import random
9
+ import os
10
+ import torch
11
 
12
+ # 模型管理器
13
  from models.model_manager import ModelManager
14
 
15
  # 初始化模型管理器
 
22
  return {}, {}, []
23
 
24
  # 打开图片
25
+ image = Image.open(image_path).convert('RGB')
26
 
27
  # 生成图像描述
28
  caption = model_manager.generate_caption(image)
29
 
30
+ # 基于图像描述进行智能分析
31
+ analysis_result = analyze_image_content(image, caption)
 
 
 
 
 
 
32
 
33
+ # 基于分析结果生成个性化建议
34
+ suggestions = generate_personalized_suggestions(analysis_result, caption)
 
 
 
 
 
35
 
36
  # 创建选择选项
37
  choices = list(suggestions.keys())
 
42
  error_result = {"错误": f"分析失败: {str(e)}"}
43
  return error_result, {}, []
44
 
45
+ def analyze_image_content(image, caption):
46
+ """基于图像和描述进行深度分析"""
47
+ # 分析图像颜色
48
+ colors = extract_dominant_colors(image)
49
+
50
+ # 根据描述推断风格类型
51
+ style_type = infer_style_from_caption(caption)
52
+
53
+ # 根据描述推断服装类别
54
+ clothing_category = infer_clothing_category(caption)
55
+
56
+ # 根据风格推荐适合场景
57
+ suitable_scenes = get_suitable_scenes(style_type)
58
+
59
+ return {
60
+ "图像描述": caption,
61
+ "检测到的颜色": colors,
62
+ "风格类型": style_type,
63
+ "服装类别": clothing_category,
64
+ "适合场景": suitable_scenes,
65
+ "图像尺寸": f"{image.width} x {image.height}",
66
+ "分析时间": time.strftime("%Y-%m-%d %H:%M:%S")
67
+ }
68
+
69
+ def extract_dominant_colors(image):
70
+ """提取图像主要颜色"""
71
+ # 调整图像大小以提高处理速度
72
+ image = image.resize((150, 150))
73
+
74
+ # 转换为numpy数组
75
+ img_array = np.array(image)
76
+
77
+ # 重塑为颜色列表
78
+ pixels = img_array.reshape(-1, 3)
79
+
80
+ # 使用KMeans聚类找到主要颜色
81
+ kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
82
+ kmeans.fit(pixels)
83
+
84
+ # 将RGB值转换为颜色名称
85
+ color_names = []
86
+ for color in kmeans.cluster_centers_:
87
+ color_name = rgb_to_color_name(color)
88
+ color_names.append(color_name)
89
+
90
+ return color_names
91
+
92
+ def rgb_to_color_name(rgb):
93
+ """将RGB值转换为颜色名称"""
94
+ r, g, b = rgb.astype(int)
95
+
96
+ # 简单的颜色映射
97
+ if r > 200 and g > 200 and b > 200:
98
+ return "白色"
99
+ elif r < 50 and g < 50 and b < 50:
100
+ return "黑色"
101
+ elif r > g and r > b:
102
+ if r > 150:
103
+ return "红色"
104
+ else:
105
+ return "深红色"
106
+ elif g > r and g > b:
107
+ if g > 150:
108
+ return "绿色"
109
+ else:
110
+ return "深绿色"
111
+ elif b > r and b > g:
112
+ if b > 150:
113
+ return "蓝色"
114
+ else:
115
+ return "深蓝色"
116
+ elif r > 150 and g > 150:
117
+ return "黄色"
118
+ elif r > 100 and b > 100:
119
+ return "紫色"
120
+ elif g > 100 and b > 100:
121
+ return "青色"
122
+ else:
123
+ return "灰色"
124
+
125
+ def infer_style_from_caption(caption):
126
+ """根据图像描述推断风格类型"""
127
+ caption_lower = caption.lower()
128
+
129
+ style_keywords = {
130
+ "商务正装": ["suit", "formal", "business", "office", "professional", "tie", "blazer", "西装", "正装", "商务"],
131
+ "休闲风": ["casual", "relaxed", "comfortable", "everyday", "jeans", "t-shirt", "休闲", "日常"],
132
+ "运动风": ["sport", "athletic", "gym", "fitness", "running", "training", "运动", "健身"],
133
+ "时尚潮流": ["fashion", "trendy", "stylish", "modern", "chic", "designer", "时尚", "潮流"],
134
+ "复古风": ["vintage", "retro", "classic", "traditional", "old-fashioned", "复古", "经典"],
135
+ "街头风": ["street", "urban", "hip-hop", "cool", "edgy", "街头", "嘻哈"],
136
+ "优雅风": ["elegant", "sophisticated", "graceful", "refined", "classy", "优雅", "高贵"]
137
+ }
138
+
139
+ for style, keywords in style_keywords.items():
140
+ if any(keyword in caption_lower for keyword in keywords):
141
+ return style
142
+
143
+ return "休闲风" # 默认风格
144
+
145
+ def infer_clothing_category(caption):
146
+ """根据描述推断服装类别"""
147
+ caption_lower = caption.lower()
148
+
149
+ categories = {
150
+ "上衣": ["shirt", "blouse", "top", "jacket", "sweater", "hoodie", "blazer", "衬衫", "上衣", "外套"],
151
+ "下装": ["pants", "jeans", "skirt", "shorts", "trousers", "裤子", "短裤", "裙子"],
152
+ "连衣裙": ["dress", "gown", "frock", "连衣裙", "礼服"],
153
+ "外套": ["coat", "jacket", "cardigan", "blazer", "外套", "大衣"],
154
+ "配饰": ["hat", "bag", "shoes", "belt", "jewelry", "帽子", "包", "鞋子", "配饰"],
155
+ "全套搭配": ["outfit", "ensemble", "look", "style", "搭配", "整套"]
156
+ }
157
+
158
+ for category, keywords in categories.items():
159
+ if any(keyword in caption_lower for keyword in keywords):
160
+ return category
161
+
162
+ return "服装单品" # 默认类别
163
+
164
+ def get_suitable_scenes(style_type):
165
+ """根据风格类型推荐适合场景"""
166
+ scene_mapping = {
167
+ "商务正装": ["办公室", "商务会议", "正式场合", "面试"],
168
+ "休闲风": ["日常出街", "朋友聚会", "购物", "咖啡约会"],
169
+ "运动风": ["健身房", "运动", "户外活动", "晨跑"],
170
+ "时尚潮流": ["时尚派对", "约会", "拍照", "社交活动"],
171
+ "复古风": ["艺术展", "文艺活动", "复古主题活动", "拍摄"],
172
+ "街头风": ["街拍", "音乐节", "朋友聚会", "潮流活动"],
173
+ "优雅风": ["晚宴", "正式聚会", "典礼", "高端场所"]
174
+ }
175
+
176
+ return scene_mapping.get(style_type, ["日常", "休闲", "约会"])
177
+
178
+ def generate_personalized_suggestions(analysis_result, caption):
179
+ """基于分析结果生成个性化建议"""
180
+ style_type = analysis_result["风格类型"]
181
+ clothing_category = analysis_result["服装类别"]
182
+ colors = analysis_result["检测到的颜色"]
183
+
184
+ suggestions = {}
185
+
186
+ # 根据检测到的风格生成建议
187
+ if style_type == "商务正装":
188
+ suggestions = {
189
+ "经典商务": f"保持{style_type}特色,搭配{colors[0]}系配饰",
190
+ "现代商务": f"在{style_type}基础上加入现代元素",
191
+ "休闲商务": f"将{style_type}与休闲元素结合",
192
+ "时尚商务": f"{style_type}融入时尚潮流元素"
193
+ }
194
+ elif style_type == "休闲风":
195
+ suggestions = {
196
+ "舒适休闲": f"强化{style_type}的舒适感,主色调{colors[0]}",
197
+ "时尚休闲": f"{style_type}加入时尚元素",
198
+ "运动休闲": f"{style_type}融入运动风格",
199
+ "优雅休闲": f"{style_type}提升优雅感"
200
+ }
201
+ elif style_type == "运动风":
202
+ suggestions = {
203
+ "专业运动": f"增强{style_type}的功能性",
204
+ "休闲运动": f"{style_type}与日常穿着结合",
205
+ "时尚运动": f"{style_type}加入潮流设计元素",
206
+ "户外运动": f"强化{style_type}的户外适应性"
207
+ }
208
+ else:
209
+ suggestions = {
210
+ f"经典{style_type}": f"保持原有{style_type}特色",
211
+ f"现代{style_type}": f"{style_type}加入现代元素",
212
+ f"融合风格": f"{style_type}与其他风格混搭",
213
+ f"个性化{style_type}": f"基于{colors[0]}色调的个性化{style_type}"
214
+ }
215
+
216
+ return suggestions
217
+
218
+ def generate_designs(selected_suggestion, progress=gr.Progress()):
219
  """根据选择的建议生成设计"""
220
  try:
221
  if not selected_suggestion:
222
  return [], gr.Radio(choices=[])
223
 
224
+ progress(0.1, desc="准备设计提示...")
225
+
226
  # 生成设计图像的提示词
227
  design_prompts = {
228
+ "经典商务": "professional business suit, modern cut, high-quality fabric, clean lines, neutral colors",
229
+ "现代商务": "contemporary business attire, innovative design, slim fit, premium materials",
230
+ "休闲商务": "business casual outfit, comfortable yet professional, versatile style",
231
+ "时尚商务": "fashion-forward business wear, runway inspired, statement piece",
232
+ "舒适休闲": "casual comfort wear, soft fabrics, relaxed fit, everyday style",
233
+ "时尚休闲": "stylish casual outfit, trendy elements, urban chic",
234
+ "运动休闲": "athleisure wear, sporty elements, comfortable and functional",
235
+ "优雅休闲": "elegant casual attire, sophisticated details, refined look",
236
+ "专业运动": "performance sportswear, technical fabrics, functional design",
237
+ "休闲运动": "casual athletic wear, versatile for sports and daily use",
238
+ "时尚运动": "fashion sportswear, trendy athletic style, streetwear influence",
239
+ "户外运动": "outdoor adventure wear, durable materials, weather-resistant",
240
+ "经典复古风": "vintage retro style, classic silhouette, nostalgic elements",
241
+ "现代复古风": "contemporary take on retro fashion, updated classics",
242
+ "融合风格": "fusion fashion, mixed styles, innovative combination",
243
+ "个性化街头风": "personalized streetwear, unique designs, urban style",
244
+ "经典优雅风": "timeless elegant fashion, sophisticated details, refined look",
245
+ "现代优雅风": "modern elegant attire, contemporary sophistication"
246
  }
247
 
248
  prompt = design_prompts.get(selected_suggestion, "fashion design, stylish clothing")
 
253
 
254
  for i in range(3): # 生成3个设计
255
  try:
256
+ progress(0.2 + i*0.25, desc=f"生成设计方案 {i+1}/3...")
257
+
258
+ # 生成真实的设计图像
259
  image = model_manager.generate_image(
260
+ prompt=f"{prompt}, design {i+1}, high detail, fashion illustration",
261
+ negative_prompt="blurry, low quality, distorted, text, watermark",
262
+ num_inference_steps=30
263
  )
264
+
265
  if image:
266
  design_images.append(image)
267
+ design_choices.append(f"{selected_suggestion} 设计方案 {i+1}")
268
  except Exception as e:
269
  print(f"生成设计 {i+1} 失败: {e}")
270
+ # 创建占位图像
271
+ width, height = 512, 512
272
+ img = Image.new('RGB', (width, height),
273
+ color=(random.randint(0, 255),
274
+ random.randint(0, 255),
275
+ random.randint(0, 255)))
276
+ design_images.append(img)
277
+ design_choices.append(f"{selected_suggestion} 设计方案 {i+1}")
278
 
279
+ progress(0.95, desc="完设计生成")
 
 
 
280
  return design_images, gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
281
 
282
  except Exception as e:
283
  print(f"设计生成错误: {e}")
284
  return [], gr.Radio(choices=[])
285
 
286
+ def generate_3d_fitting(selected_design, progress=gr.Progress()):
287
  """生成3D试穿效果"""
288
  try:
289
  if not selected_design:
290
  return None
291
 
292
+ progress(0.1, desc="准备3D试穿...")
293
+
294
  # 生成3D试穿效果的提示词
295
+ fitting_prompt = f"3D fashion fitting, virtual try-on, {selected_design}, realistic human model, full body, studio lighting"
296
+
297
+ progress(0.3, desc="生成3D模型...")
298
 
299
  # 使用模型生成3D试穿图像
300
+ if model_manager.controlnet_pipeline:
301
+ # 如果有ControlNet,使用更高级的生成
302
+ try:
303
+ # 这里简化了ControlNet的使用,实际需要姿势图等输入
304
+ image = model_manager.controlnet_pipeline(
305
+ prompt=fitting_prompt,
306
+ negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs",
307
+ num_inference_steps=35,
308
+ guidance_scale=8.0
309
+ ).images[0]
310
+ progress(0.9, desc="渲染3D效果")
311
+ return image
312
+ except Exception as e:
313
+ print(f"使用ControlNet生成失败: {e}")
314
+
315
+ # 回退到普通SD模型
316
+ progress(0.4, desc="使用标准模型生成...")
317
+ image = model_manager.generate_image(
318
  prompt=fitting_prompt,
319
+ negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs",
320
+ num_inference_steps=35
321
  )
322
 
323
+ progress(0.9, desc="完成3D渲染")
324
+ return image
325
 
326
  except Exception as e:
327
  print(f"3D试穿生成错误: {e}")
 
330
  def create_gradio_interface():
331
  """创建Gradio用户界面"""
332
 
333
+ with gr.Blocks(title="AI时尚设计师", theme="soft") as demo:
334
  gr.Markdown("# 🎨 AI时尚设计师")
335
  gr.Markdown("上传图片,获得专业的服装设计建议和3D试穿效果")
336
 
337
+ with gr.Row():
338
+ with gr.Column(scale=1):
339
+ image_input = gr.Image(type="filepath", label="上传参考图片", height=400)
340
+ analyze_btn = gr.Button("分析风格", variant="primary")
341
+
342
+ with gr.Column(scale=2):
343
+ analysis_output = gr.JSON(label="风格分析结果")
344
+
345
+ with gr.Tab("设计建议"):
346
+ suggestions_output = gr.JSON(label="个性化设计建议")
347
+ suggestion_choice = gr.Radio(label="选择设计方向", interactive=True)
348
+ generate_designs_btn = gr.Button("生成设计方案", variant="primary")
349
 
350
+ with gr.Tab("样衣设计"):
351
+ designs_gallery = gr.Gallery(label="样衣设计", columns=3, height=400)
352
+ design_choice = gr.Radio(label="选择设计方案", interactive=True)
353
+ generate_3d_btn = gr.Button("生成3D试穿效果", variant="primary")
354
 
355
+ with gr.Tab("3D试穿效果"):
356
+ fitting_result = gr.Image(label="3D试穿效果", height=500)
 
 
357
 
358
+ # 添加示例图片
359
+ examples_dir = "examples"
360
+ if os.path.exists(examples_dir):
361
+ example_files = [os.path.join(examples_dir, f) for f in os.listdir(examples_dir)
362
+ if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
363
+
364
+ gr.Examples(
365
+ examples=example_files[:4], # 最多显示4个示例
366
+ inputs=image_input,
367
+ outputs=[analysis_output, suggestions_output, suggestion_choice],
368
+ fn=upload_and_analyze,
369
+ cache_examples=True,
370
+ label="示例图片"
371
+ )
372
 
373
  # 事件绑定
374
  analyze_btn.click(
 
388
  inputs=[design_choice],
389
  outputs=[fitting_result]
390
  )
391
+
392
+ # 添加清理按钮
393
+ clear_btn = gr.Button("清理内存", variant="secondary")
394
+ clear_btn.click(
395
+ fn=model_manager.cleanup,
396
+ inputs=[],
397
+ outputs=[]
398
+ )
399
+ gr.Markdown("> **提示**: 生成图像后,点击'清理内存'按钮可以释放GPU资源")
400
 
401
  return demo
402
 
403
  if __name__ == "__main__":
404
+ # 检查并创建示例目录
405
+ examples_dir = "examples"
406
+ if not os.path.exists(examples_dir):
407
+ os.makedirs(examples_dir)
408
+ print(f"创建了示例目录: {examples_dir}")
409
+ print("请在此目录中添加示例图片以便在界面中使用")
410
+
411
  demo = create_gradio_interface()
412
+ demo.queue(concurrency_count=1) # 限制并发以避免内存问题
413
+ demo.launch(
414
+ server_name="0.0.0.0",
415
+ server_port=7860,
416
+ share=True,
417
+ favicon_path="favicon.ico" if os.path.exists("favicon.ico") else None
418
+ )