dongfang2021 commited on
Commit
61e084c
1 Parent(s): 66a0d6b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -0
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from diffusers import StableDiffusionPipeline
3
+ import torch
4
+ from PIL import Image, ImageFilter, ImageEnhance
5
+ import time
6
+ import io
7
+
8
+ def generate_image(text, style):
9
+ try:
10
+ torch.backends.cudnn.benchmark = True
11
+
12
+ # Adjust this part based on how styles are selected in your 'diffusers' library
13
+ if style.startswith('custom:'):
14
+ # Handle custom style input
15
+ text = text + "," + style
16
+ else:
17
+ text = text + "," + style
18
+
19
+ pipe = StableDiffusionPipeline.from_pretrained("IDEA-CCNL/Taiyi-Stable-Diffusion-1B-Chinese-v0.1",
20
+ torch_dtype=torch.float16)
21
+ pipe.to('cuda')
22
+
23
+ # Simulate a delay to show the loading spinner
24
+ time.sleep(3)
25
+
26
+ image = pipe(text, guidance_scale=7.5, num_inference_steps=20).images[0]
27
+ return image
28
+ except Exception as e:
29
+ st.error(f"发生错误: {str(e)}")
30
+ return None
31
+
32
+ def apply_image_filters(image, filter_type, filter_strength):
33
+ if filter_type == '模糊':
34
+ return image.filter(ImageFilter.BLUR)
35
+ elif filter_type == '锐化':
36
+ enhancer = ImageEnhance.Sharpness(image)
37
+ return enhancer.enhance(filter_strength)
38
+ elif filter_type == '亮度':
39
+ enhancer = ImageEnhance.Brightness(image)
40
+ return enhancer.enhance(filter_strength)
41
+ elif filter_type == '对比度':
42
+ enhancer = ImageEnhance.Contrast(image)
43
+ return enhancer.enhance(filter_strength)
44
+ else:
45
+ return image
46
+ # Dictionary of predefined ancient poems with names and full content
47
+ ancient_poems = {
48
+ "庐山谣": "百川东到海,何时复西归?少壮不努力,老大徒伤悲。",
49
+ "将进酒": "君不见黄河之水天上来,奔流到海不复回。\n君不见高堂明镜悲白发,朝如青丝暮成雪。",
50
+ "静夜思": "床前明月光,疑是地上霜。\n举头望明月,低头思故乡。",
51
+ # Add more poems as needed
52
+ }
53
+
54
+ def main():
55
+ # Set page title and favicon
56
+ st.set_page_config(
57
+ page_title="古诗成图",
58
+ page_icon=":art:",
59
+ layout="wide"
60
+ )
61
+
62
+ # Header and instructions
63
+ st.title("古诗成图")
64
+ st.write("欢迎使用古诗成图应用!输入一句古诗,选择图片风格,然后点击“生成图片”按钮。")
65
+
66
+ # Input for Poetry Text
67
+ text = st.text_input("请输入一句古诗:", help="在这里输入您想要转化为图片的古诗.")
68
+
69
+ # Input for Image Style
70
+ style_options = ['古风', '插画', '油画', '自然', '现代', 'custom:自定义风格']
71
+ style = st.selectbox("选择图片风格:", style_options, help="选择生成图片的风格.")
72
+
73
+ # Additional Customization Options
74
+ st.sidebar.header("图像定制选项")
75
+ filter_type = st.sidebar.selectbox("应用滤镜:", ['无', '模糊', '锐化', '亮度', '对比度'])
76
+ filter_strength = st.sidebar.slider("滤镜强度:", 0.1, 2.0, 1.0)
77
+
78
+ # Display predefined ancient poems in the sidebar
79
+ selected_poem_name = st.sidebar.selectbox("选择古诗:", list(ancient_poems.keys()), help="选择一个古诗,将其插入到输入框中.")
80
+
81
+ # Button to expand and collapse the full content of the selected poem
82
+ if st.sidebar.button("展开/收起古诗内容"):
83
+ if selected_poem_name in ancient_poems:
84
+ st.sidebar.write(f"**{selected_poem_name}**:\n{ancient_poems[selected_poem_name]}")
85
+
86
+ # Button to insert the selected poem into the text input
87
+ if st.sidebar.button("插入古诗"):
88
+ text = ancient_poems[selected_poem_name]
89
+
90
+ # Create an empty placeholder for the generated image
91
+ image_placeholder = st.empty()
92
+
93
+ # Button to Generate Image
94
+ generate_button = st.button("生成图片", help="点击此按钮生成基于古诗的艺术图片.")
95
+
96
+ # Use st.spinner to display a loading spinner
97
+ with st.spinner("正在生成图片,请稍候..."):
98
+ if generate_button:
99
+ generated_image = generate_image(text, style.lower())
100
+
101
+ if generated_image is not None:
102
+ # Apply Customization Options
103
+ customized_image = apply_image_filters(generated_image, filter_type, filter_strength)
104
+
105
+ # # Display the generated text
106
+ # st.subheader("生成的古诗文本:")
107
+ # st.text(text)
108
+
109
+ # Display the generated image
110
+ image_placeholder.image(customized_image, caption=f"生成的图片", use_column_width=True)
111
+ # Shareable link
112
+ shareable_link = st.text_input("生成的图片链接:", value="复制此链接并分享", key="shareable_link")
113
+
114
+ # Download Button for Image
115
+ if st.button("下载生成的图片"):
116
+ # Convert the image to bytes
117
+ img_bytes = io.BytesIO()
118
+ customized_image.save(img_bytes, format='PNG')
119
+
120
+ # Additional logging for debugging
121
+ print(f"Attempting to download image. Bytes length: {len(img_bytes.getvalue())}")
122
+
123
+ st.download_button(
124
+ label="下载生成的图片",
125
+ data=img_bytes.getvalue(),
126
+ file_name=f"generated_image_{style.lower()}.png",
127
+ key=f"download_button_{style.lower()}"
128
+ )
129
+
130
+ if __name__ == "__main__":
131
+ main()