lisonallen commited on
Commit
3b80791
·
1 Parent(s): a0be010

Use older Gradio version and simplest interface

Browse files
Files changed (2) hide show
  1. app.py +66 -103
  2. requirements.txt +1 -1
app.py CHANGED
@@ -12,126 +12,89 @@ logging.basicConfig(level=logging.INFO,
12
  stream=sys.stdout)
13
  logger = logging.getLogger(__name__)
14
 
15
- # 创建一个简单的示例图像,在模型加载失败或生成失败时使用
16
  def create_dummy_image():
17
- # 创建一个简单的彩色图像
18
  img = PILImage.new('RGB', (256, 256), color = (255, 100, 100))
19
  return img
20
 
21
- # 全局变量,管理模型状态
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  pipe = None
23
- MAX_SEED = np.iinfo(np.int32).max
24
 
25
- # 简化的推理函数
26
- def generate_image(prompt):
27
  global pipe
28
 
29
- try:
30
- # 懒加载模型 - 仅在第一次调用时加载
 
 
 
 
 
 
 
 
31
  if pipe is None:
32
- try:
33
- logger.info("First request - loading model...")
34
- from diffusers import DiffusionPipeline
35
- import torch
36
-
37
- device = "cuda" if torch.cuda.is_available() else "cpu"
38
- model_repo_id = "stabilityai/sdxl-turbo"
39
-
40
- logger.info(f"Using device: {device}")
41
- logger.info(f"Loading model: {model_repo_id}")
42
-
43
- if torch.cuda.is_available():
44
- torch_dtype = torch.float16
45
- else:
46
- torch_dtype = torch.float32
47
-
48
- # 优化内存使用
49
- pipe = DiffusionPipeline.from_pretrained(
50
- model_repo_id,
51
- torch_dtype=torch_dtype,
52
- variant="fp16" if torch.cuda.is_available() else None,
53
- use_safetensors=True
54
- )
55
- pipe = pipe.to(device)
56
-
57
- # 优化内存
58
- if torch.cuda.is_available():
59
- pipe.enable_attention_slicing()
60
- # 释放不必要的内存
61
- torch.cuda.empty_cache()
62
-
63
- logger.info("Model loaded successfully")
64
-
65
- except Exception as e:
66
- logger.error(f"Error loading model: {str(e)}")
67
- return create_dummy_image()
68
-
69
- # 处理空提示
70
- if not prompt or prompt.strip() == "":
71
- prompt = "A beautiful landscape"
72
- logger.info(f"Empty prompt, using default: {prompt}")
73
-
74
- logger.info(f"Generating image for prompt: {prompt}")
75
- seed = random.randint(0, MAX_SEED)
76
- generator = torch.Generator().manual_seed(seed)
77
-
78
- # 简化参数和异常处理
79
- try:
80
- # 使用最小的推理步骤以减轻资源压力
81
- image = pipe(
82
- prompt=prompt,
83
- guidance_scale=0.0, # 设为0以获得最快的推理时间
84
- num_inference_steps=1, # 减少步骤
85
- generator=generator,
86
- height=256, # 减小图像尺寸
87
- width=256 # 减小图像尺寸
88
- ).images[0]
89
-
90
- # 确保图像是有效的PIL图像
91
- if not isinstance(image, PILImage.Image):
92
- logger.warning("Converting image to PIL format")
93
- image = PILImage.fromarray(np.array(image))
94
-
95
- # 转换图像模式
96
- if image.mode != 'RGB':
97
- image = image.convert('RGB')
98
-
99
- logger.info("Image generation successful")
100
-
101
- # 释放内存
102
- if torch.cuda.is_available():
103
- torch.cuda.empty_cache()
104
-
105
- return image
106
-
107
- except Exception as e:
108
- logger.error(f"Error in image generation: {str(e)}")
109
  return create_dummy_image()
 
 
 
 
 
 
 
 
 
 
 
110
 
 
 
111
  except Exception as e:
112
- logger.error(f"Unexpected error: {str(e)}")
113
  return create_dummy_image()
114
 
115
- # 使用最简单的界面
116
- demo = gr.Interface(
117
- fn=generate_image,
118
- inputs=gr.Textbox(label="Enter your prompt"),
119
- outputs=gr.Image(label="Generated Image", type="pil"),
120
- title="SDXL Turbo Text-to-Image",
121
- description="Enter a text prompt to generate an image.",
122
- examples=["A cute cat"], # 只保留一个简单示例
123
- cache_examples=False
124
  )
125
 
126
  # 启动应用
127
  if __name__ == "__main__":
128
  try:
129
- logger.info("Starting Gradio app")
130
- demo.launch(
131
- server_name="0.0.0.0",
132
- server_port=7860,
133
- show_api=False, # 禁用API
134
- share=False
135
- )
136
  except Exception as e:
137
- logger.error(f"Error launching app: {str(e)}")
 
12
  stream=sys.stdout)
13
  logger = logging.getLogger(__name__)
14
 
15
+ # 创建一个简单的示例图像
16
  def create_dummy_image():
17
+ logger.info("Creating dummy image")
18
  img = PILImage.new('RGB', (256, 256), color = (255, 100, 100))
19
  return img
20
 
21
+ # 使用小型模型减轻负担
22
+ def get_model():
23
+ try:
24
+ from diffusers import StableDiffusionPipeline
25
+ import torch
26
+
27
+ logger.info("Loading smaller model: runwayml/stable-diffusion-v1-5")
28
+
29
+ model_id = "runwayml/stable-diffusion-v1-5"
30
+ device = "cuda" if torch.cuda.is_available() else "cpu"
31
+ logger.info(f"Using device: {device}")
32
+
33
+ if torch.cuda.is_available():
34
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
35
+ pipe = pipe.to(device)
36
+ pipe.enable_attention_slicing()
37
+ else:
38
+ pipe = StableDiffusionPipeline.from_pretrained(model_id)
39
+ pipe = pipe.to(device)
40
+
41
+ logger.info("Model loaded successfully")
42
+ return pipe
43
+ except Exception as e:
44
+ logger.error(f"Failed to load model: {e}")
45
+ return None
46
+
47
+ # 全局变量
48
  pipe = None
 
49
 
50
+ # 非常简单的功能实现
51
+ def generate(prompt):
52
  global pipe
53
 
54
+ # 如果提示为空,使用默认提示
55
+ if not prompt or prompt.strip() == "":
56
+ prompt = "a beautiful landscape"
57
+
58
+ logger.info(f"Received prompt: {prompt}")
59
+
60
+ # 第一次调用时加载模型
61
+ if pipe is None:
62
+ pipe = get_model()
63
+ # 如果模型加载失败,返回示例图像
64
  if pipe is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  return create_dummy_image()
66
+
67
+ try:
68
+ logger.info("Starting image generation")
69
+ # 使用最小的计算量生成图像
70
+ image = pipe(
71
+ prompt=prompt,
72
+ num_inference_steps=1,
73
+ guidance_scale=7.0,
74
+ height=256,
75
+ width=256
76
+ ).images[0]
77
 
78
+ logger.info("Image generated successfully")
79
+ return image
80
  except Exception as e:
81
+ logger.error(f"Generation failed: {e}")
82
  return create_dummy_image()
83
 
84
+ # 极简界面
85
+ iface = gr.Interface(
86
+ fn=generate,
87
+ inputs="text",
88
+ outputs="image",
89
+ title="Simple Text-to-Image",
90
+ description="Type a prompt to generate an image.",
91
+ examples=["a cat", "mountain landscape"]
 
92
  )
93
 
94
  # 启动应用
95
  if __name__ == "__main__":
96
  try:
97
+ logger.info("Starting Gradio interface")
98
+ iface.launch(server_name="0.0.0.0")
 
 
 
 
 
99
  except Exception as e:
100
+ logger.error(f"Failed to launch: {e}")
requirements.txt CHANGED
@@ -2,5 +2,5 @@ accelerate==0.21.0
2
  diffusers==0.20.0
3
  torch==2.0.1
4
  transformers==4.34.0
5
- gradio==3.32.0
6
  Pillow==10.0.0
 
2
  diffusers==0.20.0
3
  torch==2.0.1
4
  transformers==4.34.0
5
+ gradio==3.24.1
6
  Pillow==10.0.0