boheng.xie commited on
Commit
b733220
·
1 Parent(s): 78e590c

change main file

Browse files
Files changed (1) hide show
  1. app.py +59 -22
app.py CHANGED
@@ -2,6 +2,7 @@
2
  import gradio as gr
3
  from diffusers import StableDiffusionPipeline
4
  import torch
 
5
 
6
  # 在Space环境中检测设备
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -12,31 +13,67 @@ model = StableDiffusionPipeline.from_pretrained(
12
  "stabilityai/sd-turbo",
13
  torch_dtype=torch.float16 if device == "cuda" else torch.float32,
14
  use_safetensors=True,
15
- safety_checker=None, # 根据需要可开启或关闭
16
  variant="fp16" if device == "cuda" else None,
17
  low_cpu_mem_usage=True
18
- )
19
- model = model.to(device)
20
 
21
- def generate(prompt):
 
 
 
 
 
 
22
  if not prompt:
23
- return None, "请输入有效的提示词"
 
 
 
 
 
 
 
 
 
 
 
24
  try:
25
- image = model(prompt, num_inference_steps=4).images[0]
26
- return image, "生成成功!"
 
 
 
 
 
 
 
 
27
  except Exception as e:
28
- return None, f"生成失败: {str(e)}"
29
-
30
- # 基础界面
31
- interface = gr.Interface(
32
- fn=generate,
33
- inputs=gr.Textbox(label="输入表情包描述"),
34
- outputs=[
35
- gr.Image(label="生成结果"),
36
- gr.Textbox(label="状态")
37
- ],
38
- examples=[["一只生气的猫"], ["跳舞的香蕉"]]
39
- )
40
-
41
- # Hugging Face Space推荐的启动方式
42
- interface.launch(share=False, server_name="0.0.0.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
  from diffusers import StableDiffusionPipeline
4
  import torch
5
+ from PIL import Image, ImageFilter
6
 
7
  # 在Space环境中检测设备
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
13
  "stabilityai/sd-turbo",
14
  torch_dtype=torch.float16 if device == "cuda" else torch.float32,
15
  use_safetensors=True,
16
+ safety_checker=None,
17
  variant="fp16" if device == "cuda" else None,
18
  low_cpu_mem_usage=True
19
+ ).to(device)
 
20
 
21
+ # 性能优化
22
+ if device == "cuda":
23
+ model.enable_xformers_memory_efficient_attention()
24
+ model.enable_model_cpu_offload()
25
+
26
+ def validate_input(prompt):
27
+ """输入验证"""
28
  if not prompt:
29
+ raise ValueError("请输入有效描述")
30
+ if len(prompt) > 100:
31
+ raise ValueError("提示词过长(最多100字符)")
32
+ if not any('\u4e00' <= c <= '\u9fff' for c in prompt):
33
+ raise ValueError("请至少包含一个中文字符")
34
+ return prompt.strip()
35
+
36
+ def post_process(image):
37
+ """图像后处理"""
38
+ return image.filter(ImageFilter.SHARPEN).filter(ImageFilter.UnsharpMask(radius=2, percent=150))
39
+
40
+ def generate(prompt):
41
  try:
42
+ valid_prompt = validate_input(prompt)
43
+ steps = 4 if device == "cuda" else 15
44
+ image = model(
45
+ valid_prompt,
46
+ num_inference_steps=steps,
47
+ guidance_scale=2.0,
48
+ height=768 if device == "cuda" else 512,
49
+ width=768 if device == "cuda" else 512
50
+ ).images[0]
51
+ return post_process(image), "🎉 生成成功!点击图片可下载"
52
  except Exception as e:
53
+ return None, f" 错误:{str(e)}"
54
+
55
+ # 界面构建
56
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
57
+ gr.Markdown("## 🎭 AI表情包工坊")
58
+
59
+ with gr.Row():
60
+ input_box = gr.Textbox(label="输入描述", placeholder="例如:打工人的周一早晨...")
61
+ generate_btn = gr.Button("生成", variant="primary")
62
+
63
+ with gr.Row():
64
+ image_out = gr.Image(label="生成结果", show_label=False, type="pil")
65
+ status_box = gr.Textbox(label="状态", interactive=False)
66
+
67
+ gr.Examples(
68
+ examples=[["熊猫头说'我太难了'"], ["流泪猫猫头配文'真的栓Q'"]],
69
+ inputs=input_box
70
+ )
71
+
72
+ generate_btn.click(
73
+ generate,
74
+ inputs=input_box,
75
+ outputs=[image_out, status_box]
76
+ )
77
+
78
+ if __name__ == "__main__":
79
+ demo.launch(server_name="0.0.0.0")