Humphreykowl commited on
Commit
3231dea
·
verified ·
1 Parent(s): 49dfa5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -225
app.py CHANGED
@@ -1,31 +1,77 @@
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
- # 初始化模型管理器
16
- model_manager = ModelManager()
 
 
 
 
 
 
 
 
17
 
18
  def upload_and_analyze(image_path):
19
  """分析上传的图片"""
20
  try:
21
  if image_path is None:
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)
@@ -40,87 +86,94 @@ def upload_and_analyze(image_path):
40
 
41
  except Exception as e:
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
  """根据图像描述推断风格类型"""
@@ -177,43 +230,51 @@ def get_suitable_scenes(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
  """根据选择的建议生成设计"""
@@ -232,17 +293,7 @@ def generate_designs(selected_suggestion, progress=gr.Progress()):
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")
@@ -255,24 +306,27 @@ def generate_designs(selected_suggestion, progress=gr.Progress()):
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
 
@@ -280,7 +334,7 @@ def generate_designs(selected_suggestion, progress=gr.Progress()):
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()):
@@ -294,38 +348,25 @@ def generate_3d_fitting(selected_design, progress=gr.Progress()):
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}")
328
- return None
 
 
329
 
330
  def create_gradio_interface():
331
  """创建Gradio用户界面"""
@@ -355,21 +396,10 @@ def create_gradio_interface():
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(
375
  fn=upload_and_analyze,
@@ -389,69 +419,30 @@ def create_gradio_interface():
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
- )
419
- # 在 create_gradio_interface() 函数中添加内存管理按钮
420
- def create_gradio_interface():
421
- with gr.Blocks(title="AI时尚设计师", theme="soft") as demo:
422
- # ... [现有代码] ...
423
-
424
- # 添加内存管理部分
425
- with gr.Row():
426
- gr.Markdown("### 内存管理")
427
- unload_caption_btn = gr.Button("卸载描述模型")
428
- unload_sd_btn = gr.Button("卸载设计模型")
429
- unload_controlnet_btn = gr.Button("卸载3D模型")
430
- full_cleanup_btn = gr.Button("清理所有模型", variant="stop")
431
-
432
- # 内存管理事件
433
- unload_caption_btn.click(
434
- fn=lambda: model_manager.unload_model("caption"),
435
- inputs=[],
436
- outputs=[]
437
- )
438
-
439
- unload_sd_btn.click(
440
- fn=lambda: model_manager.unload_model("sd"),
441
- inputs=[],
442
- outputs=[]
443
- )
444
-
445
- unload_controlnet_btn.click(
446
- fn=lambda: model_manager.unload_model("controlnet"),
447
- inputs=[],
448
- outputs=[]
449
- )
450
-
451
- full_cleanup_btn.click(
452
- fn=model_manager.cleanup,
453
- inputs=[],
454
- outputs=[]
455
- )
456
-
457
- return demo
 
1
+ # app.py (Gradio界面) - 优化版
2
  import gradio as gr
3
+ import os
4
+ import sys
5
+ import logging
6
  from PIL import Image
7
  import numpy as np
8
  from sklearn.cluster import KMeans
9
  import time
10
  import random
11
+ import warnings
12
+
13
+ # 抑制警告
14
+ warnings.filterwarnings("ignore")
15
+
16
+ # 设置日志
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # 检查模型管理器是否存在
21
+ try:
22
+ from models.model_manager import ModelManager
23
+ MODELS_AVAILABLE = True
24
+ except ImportError as e:
25
+ logger.warning(f"模型管理器导入失败: {e}")
26
+ logger.info("将使用简化版本运行")
27
+ MODELS_AVAILABLE = False
28
+ ModelManager = None
29
 
30
+ class SimpleModelManager:
31
+ """简化的模型管理器,用于演示模式"""
32
+ def __init__(self):
33
+ self.device = "cpu"
34
+ logger.info("使用简化模型管理器")
35
+
36
+ def generate_caption(self, image):
37
+ return "这是一件时尚的服装设计,具有现代感和优雅的风格。"
38
+
39
+ def generate_image(self, prompt, **kwargs):
40
+ # 创建占位图像
41
+ width, height = kwargs.get('width', 512), kwargs.get('height', 512)
42
+ color = (random.randint(100, 255), random.randint(100, 255), random.randint(100, 255))
43
+ img = Image.new('RGB', (width, height), color=color)
44
+ return img
45
+
46
+ def cleanup(self):
47
+ pass
48
 
49
+ # 根据是否有模型选择管理器
50
+ if MODELS_AVAILABLE:
51
+ try:
52
+ model_manager = ModelManager()
53
+ logger.info("使用完整模型管理器")
54
+ except Exception as e:
55
+ logger.error(f"初始化完整模型管理器失败: {e}")
56
+ model_manager = SimpleModelManager()
57
+ else:
58
+ model_manager = SimpleModelManager()
59
 
60
  def upload_and_analyze(image_path):
61
  """分析上传的图片"""
62
  try:
63
  if image_path is None:
64
+ return {}, {}, gr.Radio(choices=[])
65
 
66
  # 打开图片
67
  image = Image.open(image_path).convert('RGB')
68
 
69
  # 生成图像描述
70
+ try:
71
+ caption = model_manager.generate_caption(image)
72
+ except Exception as e:
73
+ logger.error(f"生成描述失败: {e}")
74
+ caption = "时尚服装设计"
75
 
76
  # 基于图像描述进行智能分析
77
  analysis_result = analyze_image_content(image, caption)
 
86
 
87
  except Exception as e:
88
  error_result = {"错误": f"分析失败: {str(e)}"}
89
+ logger.error(f"上传分析失败: {e}")
90
+ return error_result, {}, gr.Radio(choices=[])
91
 
92
  def analyze_image_content(image, caption):
93
  """基于图像和描述进行深度分析"""
94
+ try:
95
+ # 分析图像颜色
96
+ colors = extract_dominant_colors(image)
97
+
98
+ # 根据描述推断风格类型
99
+ style_type = infer_style_from_caption(caption)
100
+
101
+ # 根据描述推断服装类别
102
+ clothing_category = infer_clothing_category(caption)
103
+
104
+ # 根据风格推荐适合场景
105
+ suitable_scenes = get_suitable_scenes(style_type)
106
+
107
+ return {
108
+ "图像描述": caption,
109
+ "检测到的颜色": colors,
110
+ "风格": style_type,
111
+ "服装类别": clothing_category,
112
+ "适合场景": suitable_scenes,
113
+ "图像尺寸": f"{image.width} x {image.height}",
114
+ "分析时间": time.strftime("%Y-%m-%d %H:%M:%S")
115
+ }
116
+ except Exception as e:
117
+ logger.error(f"图像内容分析失败: {e}")
118
+ return {
119
+ "错误": f"分析失败: {str(e)}",
120
+ "图像描述": caption,
121
+ "风格类型": "休闲风"
122
+ }
123
 
124
  def extract_dominant_colors(image):
125
  """提取图像主要颜色"""
126
+ try:
127
+ # 调整图像大小以提高处理速度
128
+ image = image.resize((150, 150))
129
+
130
+ # 转换为numpy数组
131
+ img_array = np.array(image)
132
+
133
+ # 重塑为颜色列表
134
+ pixels = img_array.reshape(-1, 3)
135
+
136
+ # 使用KMeans聚类找到主要颜色
137
+ kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
138
+ kmeans.fit(pixels)
139
+
140
+ # 将RGB值转换为颜色名称
141
+ color_names = []
142
+ for color in kmeans.cluster_centers_:
143
+ color_name = rgb_to_color_name(color)
144
+ color_names.append(color_name)
145
+
146
+ return color_names
147
+ except Exception as e:
148
+ logger.error(f"颜色提取失败: {e}")
149
+ return ["主色调", "辅助色", "点缀色"]
150
 
151
  def rgb_to_color_name(rgb):
152
  """将RGB值转换为颜色名称"""
153
+ try:
154
+ r, g, b = rgb.astype(int)
155
+
156
+ # 简单的颜色映射
157
+ if r > 200 and g > 200 and b > 200:
158
+ return "白色"
159
+ elif r < 50 and g < 50 and b < 50:
160
+ return "黑色"
161
+ elif r > g and r > b:
162
+ return "红色" if r > 150 else "深红色系"
163
+ elif g > r and g > b:
164
+ return "绿色系" if g > 150 else "绿"
165
+ elif b > r and b > g:
166
+ return "蓝色系" if b > 150 else "深蓝色系"
167
+ elif r > 150 and g > 150:
168
+ return "黄色系"
169
+ elif r > 100 and b > 100:
170
+ return "紫色系"
171
+ elif g > 100 and b > 100:
172
+ return ""
173
  else:
174
+ return ""
175
+ except:
176
+ return "未知"
 
 
 
 
 
 
177
 
178
  def infer_style_from_caption(caption):
179
  """根据图像描述推断风格类型"""
 
230
 
231
  def generate_personalized_suggestions(analysis_result, caption):
232
  """基于分析结果生成个性化建议"""
233
+ try:
234
+ style_type = analysis_result.get("风格", "休闲风")
235
+ clothing_category = analysis_result.get("服装类别", "服装单品")
236
+ colors = analysis_result.get("检测到的颜色", ["主色调"])
237
+
238
+ suggestions = {}
239
+
240
+ # 根据检测到的风格生成建议
241
+ if style_type == "商务正装":
242
+ suggestions = {
243
+ "经典商务": f"保持{style_type}特色,搭配{colors[0]}系配饰",
244
+ "现代商务": f"{style_type}基础上加入现代元素",
245
+ "休闲商务": f"{style_type}与休闲元素结合",
246
+ "时尚商务": f"{style_type}融入时尚潮流元素"
247
+ }
248
+ elif style_type == "休闲风":
249
+ suggestions = {
250
+ "舒适休闲": f"强化{style_type}的舒适感,主色调{colors[0]}",
251
+ "时尚休闲": f"{style_type}时尚元素",
252
+ "运动休闲": f"{style_type}融入运动风格",
253
+ "优雅休闲": f"{style_type}提升优雅感"
254
+ }
255
+ elif style_type == "运动风":
256
+ suggestions = {
257
+ "专业运动": f"增强{style_type}的功能性",
258
+ "休闲运动": f"{style_type}与日常穿着结合",
259
+ "时尚运动": f"{style_type}加入潮流设计元素",
260
+ "户外运动": f"强化{style_type}的户外适应性"
261
+ }
262
+ else:
263
+ suggestions = {
264
+ f"经典{style_type}": f"保持原有{style_type}特色",
265
+ f"现代{style_type}": f"{style_type}加入现代元素",
266
+ f"融合风格": f"{style_type}与其他风格混搭",
267
+ f"个性化{style_type}": f"基于{colors[0]}色调的个性化{style_type}"
268
+ }
269
+
270
+ return suggestions
271
+ except Exception as e:
272
+ logger.error(f"生成建议失败: {e}")
273
+ return {
274
+ "经典设计": "传统经典的设计风格",
275
+ "现代风格": "融入现代设计元素",
276
+ "个性化": "独特的个性化设计"
277
  }
 
 
278
 
279
  def generate_designs(selected_suggestion, progress=gr.Progress()):
280
  """根据选择的建议生成设计"""
 
293
  "舒适休闲": "casual comfort wear, soft fabrics, relaxed fit, everyday style",
294
  "时尚休闲": "stylish casual outfit, trendy elements, urban chic",
295
  "运动休闲": "athleisure wear, sporty elements, comfortable and functional",
296
+ "优雅休闲": "elegant casual attire, sophisticated details, refined look"
 
 
 
 
 
 
 
 
 
 
297
  }
298
 
299
  prompt = design_prompts.get(selected_suggestion, "fashion design, stylish clothing")
 
306
  try:
307
  progress(0.2 + i*0.25, desc=f"生成设计方案 {i+1}/3...")
308
 
309
+ # 生成设计图像
310
  image = model_manager.generate_image(
311
  prompt=f"{prompt}, design {i+1}, high detail, fashion illustration",
312
  negative_prompt="blurry, low quality, distorted, text, watermark",
313
+ num_inference_steps=20, # 减少步数以提高速度
314
+ width=512,
315
+ height=512
316
  )
317
 
318
  if image:
319
  design_images.append(image)
320
  design_choices.append(f"{selected_suggestion} 设计方案 {i+1}")
321
+
322
  except Exception as e:
323
+ logger.error(f"生成设计 {i+1} 失败: {e}")
324
  # 创建占位图像
325
  width, height = 512, 512
326
  img = Image.new('RGB', (width, height),
327
+ color=(random.randint(100, 200),
328
+ random.randint(100, 200),
329
+ random.randint(100, 200)))
330
  design_images.append(img)
331
  design_choices.append(f"{selected_suggestion} 设计方案 {i+1}")
332
 
 
334
  return design_images, gr.Radio(choices=design_choices, value=design_choices[0] if design_choices else None)
335
 
336
  except Exception as e:
337
+ logger.error(f"设计生成错误: {e}")
338
  return [], gr.Radio(choices=[])
339
 
340
  def generate_3d_fitting(selected_design, progress=gr.Progress()):
 
348
  # 生成3D试穿效果的提示词
349
  fitting_prompt = f"3D fashion fitting, virtual try-on, {selected_design}, realistic human model, full body, studio lighting"
350
 
351
+ progress(0.5, desc="生成3D效果...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
+ # 生成图像
 
354
  image = model_manager.generate_image(
355
  prompt=fitting_prompt,
356
  negative_prompt="blurry, distorted, low quality, unrealistic, extra limbs",
357
+ num_inference_steps=25,
358
+ width=512,
359
+ height=768 # 适合全身图像
360
  )
361
 
362
  progress(0.9, desc="完成3D渲染")
363
  return image
364
 
365
  except Exception as e:
366
+ logger.error(f"3D试穿生成错误: {e}")
367
+ # 创建占位图像
368
+ img = Image.new('RGB', (512, 768), color=(200, 200, 200))
369
+ return img
370
 
371
  def create_gradio_interface():
372
  """创建Gradio用户界面"""
 
396
  with gr.Tab("3D试穿效果"):
397
  fitting_result = gr.Image(label="3D试穿效果", height=500)
398
 
399
+ # 内存管理
400
+ with gr.Row():
401
+ cleanup_btn = gr.Button("清理内存", variant="secondary")
 
 
402
 
 
 
 
 
 
 
 
 
 
403
  # 事件绑定
404
  analyze_btn.click(
405
  fn=upload_and_analyze,
 
419
  outputs=[fitting_result]
420
  )
421
 
422
+ cleanup_btn.click(
 
 
423
  fn=model_manager.cleanup,
424
  inputs=[],
425
  outputs=[]
426
  )
427
+
428
+ gr.Markdown("> **提示**: 如果遇到内存问题,请点击'清理内存'按钮")
429
 
430
  return demo
431
 
432
  if __name__ == "__main__":
433
+ # 检查环境
434
+ logger.info(f"Python版本: {sys.version}")
435
+ logger.info(f"当前工作目录: {os.getcwd()}")
 
 
 
436
 
437
+ # 创建并启动界面
438
  demo = create_gradio_interface()
439
+ demo.queue(
440
+ concurrency_count=1, # 限制并发
441
+ max_size=10 # 队列大小
442
+ )
443
  demo.launch(
444
  server_name="0.0.0.0",
445
+ server_port=7860,
446
+ share=False, # 在Spaces环境中设为False
447
+ show_error=True
448
+ )