Alpaca233 commited on
Commit
75c2120
1 Parent(s): 6a0e223

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -0
app.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import random
4
+ import re
5
+ import string
6
+
7
+ import gradio as gr
8
+
9
+ import openai
10
+ from icrawler import ImageDownloader
11
+ from icrawler.builtin import GoogleImageCrawler, BingImageCrawler
12
+ from uuid import uuid4
13
+ from pptx import Presentation
14
+
15
+ bad_coding_practice = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in
16
+ range(16))
17
+
18
+
19
+ def refresh_bad_coding_practice():
20
+ global bad_coding_practice
21
+ bad_coding_practice = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
22
+ for _ in range(16))
23
+ return
24
+
25
+
26
+ class PrefixNameDownloader(ImageDownloader):
27
+
28
+ def get_filename(self, task, default_ext):
29
+ filename = super(PrefixNameDownloader, self).get_filename(
30
+ task, default_ext)
31
+ print(bad_coding_practice)
32
+ return 'prefix_' + bad_coding_practice + filename
33
+
34
+
35
+ def generate_ppt(file, topic, slide_length, api_key):
36
+ print(file.name)
37
+
38
+ root = Presentation(file.name)
39
+
40
+ openai.api_key = api_key
41
+
42
+ message = f"""
43
+ Create content for a slideshow presentation.
44
+ The content's topic is {topic}.
45
+ The slideshow is {slide_length} slides long.
46
+ The content is written in the language of the content I give you above.
47
+
48
+
49
+ You are allowed to use the following slide types:
50
+
51
+ Slide types:
52
+ Title Slide - (Title, Subtitle)
53
+ Content Slide - (Title, Content)
54
+ Image Slide - (Title, Content, Image)
55
+ Thanks Slide - (Title)
56
+
57
+ Put this tag before the Title Slide: [L_TS]
58
+ Put this tag before the Content Slide: [L_CS]
59
+ Put this tag before the Image Slide: [L_IS]
60
+ Put this tag before the Thanks Slide: [L_THS]
61
+
62
+ Put "[SLIDEBREAK]" after each slide
63
+
64
+ For example:
65
+ [L_TS]
66
+ [TITLE]Mental Health[/TITLE]
67
+
68
+ [SLIDEBREAK]
69
+
70
+ [L_CS]
71
+ [TITLE]Mental Health Definition[/TITLE]
72
+ [CONTENT]
73
+ 1. Definition: A person’s condition with regard to their psychological and emotional well-being
74
+ 2. Can impact one's physical health
75
+ 3. Stigmatized too often.
76
+ [/CONTENT]
77
+
78
+ [SLIDEBREAK]
79
+
80
+ Put this tag before the Title: [TITLE]
81
+ Put this tag after the Title: [/TITLE]
82
+ Put this tag before the Subitle: [SUBTITLE]
83
+ Put this tag after the Subtitle: [/SUBTITLE]
84
+ Put this tag before the Content: [CONTENT]
85
+ Put this tag after the Content: [/CONTENT]
86
+ Put this tag before the Image: [IMAGE]
87
+ Put this tag after the Image: [/IMAGE]
88
+
89
+ Elaborate on the Content, provide as much information as possible.
90
+ You put a [/CONTENT] at the end of the Content.
91
+ Do not reply as if you are talking about the slideshow itself. (ex. "Include pictures here about...")
92
+ Do not include any special characters (?, !, ., :, ) in the Title.
93
+ Do not include any additional information in your response and stick to the format."""
94
+
95
+ openai.proxy = {'http': "http://127.0.0.1:8001", 'https': 'http://127.0.0.1:8001'}
96
+ response = openai.ChatCompletion.create(
97
+ model="gpt-3.5-turbo",
98
+ messages=[
99
+ {"role": "user", "content": message}
100
+ ]
101
+ )
102
+
103
+ # """ Ref for slide types:
104
+ # 0 -> title and subtitle
105
+ # 1 -> title and content
106
+ # 2 -> section header
107
+ # 3 -> two content
108
+ # 4 -> Comparison
109
+ # 5 -> Title only
110
+ # 6 -> Blank
111
+ # 7 -> Content with caption
112
+ # 8 -> Pic with caption
113
+ # """
114
+
115
+ def delete_all_slides():
116
+ for i in range(len(root.slides) - 1, -1, -1):
117
+ r_id = root.slides._sldIdLst[i].rId
118
+ root.part.drop_rel(r_id)
119
+ del root.slides._sldIdLst[i]
120
+
121
+ def create_title_slide(title, subtitle):
122
+ layout = root.slide_layouts[0]
123
+ slide = root.slides.add_slide(layout)
124
+ slide.shapes.title.text = title
125
+ slide.placeholders[1].text = subtitle
126
+
127
+ def create_section_header_slide(title):
128
+ layout = root.slide_layouts[2]
129
+ slide = root.slides.add_slide(layout)
130
+ slide.shapes.title.text = title
131
+
132
+ def create_title_and_content_slide(title, content):
133
+ layout = root.slide_layouts[1]
134
+ slide = root.slides.add_slide(layout)
135
+ slide.shapes.title.text = title
136
+ slide.placeholders[1].text = content
137
+
138
+ def create_title_and_content_and_image_slide(title, content, image_query):
139
+ layout = root.slide_layouts[8]
140
+ slide = root.slides.add_slide(layout)
141
+ slide.shapes.title.text = title
142
+ slide.placeholders[2].text = content
143
+ refresh_bad_coding_practice()
144
+ bing_crawler = BingImageCrawler(downloader_cls=PrefixNameDownloader, storage={'root_dir': os.getcwd()})
145
+ bing_crawler.crawl(keyword=image_query, max_num=1)
146
+ dir_path = os.path.dirname(os.path.realpath(__file__))
147
+ file_name = glob.glob(f"prefix_{bad_coding_practice}*")
148
+ print(file_name)
149
+ img_path = os.path.join(dir_path, file_name[0])
150
+ slide.shapes.add_picture(img_path, slide.placeholders[1].left, slide.placeholders[1].top,
151
+ slide.placeholders[1].width, slide.placeholders[1].height)
152
+
153
+ def find_text_in_between_tags(text, start_tag, end_tag):
154
+ start_pos = text.find(start_tag)
155
+ end_pos = text.find(end_tag)
156
+ result = []
157
+ while start_pos > -1 and end_pos > -1:
158
+ text_between_tags = text[start_pos + len(start_tag):end_pos]
159
+ result.append(text_between_tags)
160
+ start_pos = text.find(start_tag, end_pos + len(end_tag))
161
+ end_pos = text.find(end_tag, start_pos)
162
+ res1 = "".join(result)
163
+ res2 = re.sub(r"\[IMAGE\].*?\[/IMAGE\]", '', res1)
164
+ if len(result) > 0:
165
+ return res2
166
+ else:
167
+ return ""
168
+
169
+ def search_for_slide_type(text):
170
+ tags = ["[L_TS]", "[L_CS]", "[L_IS]", "[L_THS]"]
171
+ found_text = next((s for s in tags if s in text), None)
172
+ return found_text
173
+
174
+ def parse_response(reply):
175
+ list_of_slides = reply.split("[SLIDEBREAK]")
176
+ for slide in list_of_slides:
177
+ slide_type = search_for_slide_type(slide)
178
+ if slide_type == "[L_TS]":
179
+ create_title_slide(find_text_in_between_tags(str(slide), "[TITLE]", "[/TITLE]"),
180
+ find_text_in_between_tags(str(slide), "[SUBTITLE]", "[/SUBTITLE]"))
181
+ elif slide_type == "[L_CS]":
182
+ create_title_and_content_slide("".join(find_text_in_between_tags(str(slide), "[TITLE]", "[/TITLE]")),
183
+ "".join(find_text_in_between_tags(str(slide), "[CONTENT]",
184
+ "[/CONTENT]")))
185
+ elif slide_type == "[L_IS]":
186
+ create_title_and_content_and_image_slide("".join(find_text_in_between_tags(str(slide), "[TITLE]",
187
+ "[/TITLE]")),
188
+ "".join(find_text_in_between_tags(str(slide), "[CONTENT]",
189
+ "[/CONTENT]")),
190
+ "".join(find_text_in_between_tags(str(slide), "[IMAGE]",
191
+ "[/IMAGE]")))
192
+ elif slide_type == "[L_THS]":
193
+ create_section_header_slide("".join(find_text_in_between_tags(str(slide), "[TITLE]", "[/TITLE]")))
194
+
195
+ def find_title():
196
+ return root.slides[0].shapes.title.text
197
+
198
+ delete_all_slides()
199
+
200
+ print(response)
201
+
202
+ parse_response(response['choices'][0]['message']['content'])
203
+
204
+ name_ = str(uuid4()).replace('-', '')
205
+
206
+ root.save(f"./{name_}.pptx")
207
+
208
+ print("done")
209
+
210
+ dir_path = "./"
211
+ prefix = "prefix_"
212
+
213
+ for file_name in os.listdir(dir_path):
214
+ if file_name.startswith(prefix):
215
+ file_path = os.path.join(dir_path, file_name)
216
+ if os.path.isfile(file_path):
217
+ os.remove(file_path)
218
+
219
+ return f"./{name_}.pptx"
220
+
221
+
222
+ with gr.Blocks(title="ChatGPT PPT框架生成") as demo:
223
+ gr.Markdown("""<h1><center>ChatGPT PPT框架生成</center></h1>""")
224
+ with gr.Row():
225
+ with gr.Column():
226
+ openai_token = gr.Textbox(label="OpenAI API Key")
227
+ topic = gr.Textbox(label="PPT的主题或内容")
228
+ length = gr.Slider(minimum=1, maximum=20, value=6, label="生成的PPT页数", step=1)
229
+ theme = gr.File(value="./theme.pptx", file_types=['pptx', 'ppt'], label="PPT模版")
230
+ output_file = gr.File(interactive=False)
231
+
232
+ topic.submit(
233
+ fn=generate_ppt,
234
+ inputs=[theme, topic, length, openai_token],
235
+ outputs=[output_file]
236
+ )
237
+
238
+ submit = gr.Button("生成")
239
+ submit.click(
240
+ fn=generate_ppt,
241
+ inputs=[theme, topic, length, openai_token],
242
+ outputs=[output_file]
243
+ )
244
+
245
+ if __name__ == "__main__":
246
+ demo.launch()