lijiele commited on
Commit
1666216
·
1 Parent(s): d9f0b53

add gpt-story-genius file

Browse files
Files changed (7) hide show
  1. .env.example +11 -0
  2. LICENSE +201 -0
  3. author.py +144 -0
  4. config.py +48 -0
  5. requirements.txt +6 -0
  6. run.py +74 -0
  7. write_story.py +384 -0
.env.example ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenAI 接口代理地址,(可选配置)
2
+ OPENAI_API_BASE="your-openai-proxy-url"
3
+
4
+ # * 配置你的 OpenAI key(建议使用GPT-4正式账号,临时账号有每分钟3次请求限制)
5
+ OPENAI_API_KEY="your-openai-api-key"
6
+
7
+ # * 生成小说封面,具体可访问 https://platform.stability.ai/ 地址申请key
8
+ STABILITY_API_KEY="your-stablity-api-key"
9
+
10
+ # 配置你的 Claude2 API Key(可选配置)
11
+ ANTHROPIC_API_KEY="your-anthropic-api-key"
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
author.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ebooklib import epub
2
+ import base64
3
+ import os
4
+ import requests
5
+ from config import completion_with_backoff
6
+ from config import stability_api_key
7
+
8
+
9
+ def generate_cover_prompt(plot):
10
+ response = completion_with_backoff(
11
+ model="gpt-3.5-turbo-16k",
12
+ messages=[
13
+ {"role": "system",
14
+ "content": "You are a creative assistant that writes a spec for the cover art of a book, based on the book's plot."},
15
+ {"role": "user",
16
+ "content": f"Plot: {plot}\n\n--\n\nDescribe the cover we should create, based on the plot. This should be two sentences long, maximum."}
17
+ ]
18
+ )
19
+ return response['choices'][0]['message']['content']
20
+
21
+
22
+ def create_cover_image(plot):
23
+ plot = str(generate_cover_prompt(plot))
24
+
25
+ engine_id = "stable-diffusion-xl-beta-v2-2-2"
26
+ api_host = os.getenv('API_HOST', 'https://api.stability.ai')
27
+ api_key = stability_api_key
28
+
29
+ if api_key is None:
30
+ raise Exception("Missing Stability API key.")
31
+
32
+ response = requests.post(
33
+ f"{api_host}/v1/generation/{engine_id}/text-to-image",
34
+ headers={
35
+ "Content-Type": "application/json",
36
+ "Accept": "application/json",
37
+ "Authorization": f"Bearer {api_key}"
38
+ },
39
+ json={
40
+ "text_prompts": [
41
+ {
42
+ "text": plot
43
+ }
44
+ ],
45
+ "cfg_scale": 7,
46
+ "clip_guidance_preset": "FAST_BLUE",
47
+ "height": 768,
48
+ "width": 512,
49
+ "samples": 1,
50
+ "steps": 30,
51
+ },
52
+ )
53
+
54
+ if response.status_code != 200:
55
+ raise Exception("Non-200 response: " + str(response.text))
56
+
57
+ data = response.json()
58
+
59
+ # 检查目录是否存在,如果不存在则创建
60
+ directory = "./cover/"
61
+ if not os.path.exists(directory):
62
+ os.makedirs(directory)
63
+
64
+ for i, image in enumerate(data["artifacts"]):
65
+ image_bytes = base64.b64decode(image["base64"])
66
+ file_path = f"./cover/cover_{i}.png" # 修改为您想要的文件路径
67
+ with open(file_path, "wb") as f:
68
+ f.write(image_bytes)
69
+
70
+ return file_path
71
+
72
+
73
+ def create_epub(title, author, chapters, cover_image_path='cover.png'):
74
+ book = epub.EpubBook()
75
+
76
+ # Set metadata
77
+ book.set_identifier('id123456')
78
+ book.set_title(title)
79
+ book.set_language('zh-cn')
80
+ book.add_author(author)
81
+
82
+ # Add cover image
83
+ with open(cover_image_path, 'rb') as cover_file:
84
+ cover_image = cover_file.read()
85
+ book.set_cover('cover.png', cover_image)
86
+
87
+ # Create chapters and add them to the book
88
+ epub_chapters = []
89
+ for i, chapter_dict in enumerate(chapters):
90
+ full_chapter_title = list(chapter_dict.keys())[0]
91
+ chapter_content = list(chapter_dict.values())[0]
92
+ if ' - ' in full_chapter_title:
93
+ chapter_title = full_chapter_title.split(' - ')[1]
94
+ else:
95
+ chapter_title = full_chapter_title
96
+
97
+ chapter_file_name = f'chapter_{i + 1}.xhtml'
98
+ epub_chapter = epub.EpubHtml(title=chapter_title, file_name=chapter_file_name, lang='zh-cn')
99
+
100
+ # Add paragraph breaks
101
+ formatted_content = ''.join(
102
+ f'<p>{paragraph.strip()}</p>' for paragraph in chapter_content.split('\n') if paragraph.strip())
103
+
104
+ epub_chapter.content = f'<h1>{chapter_title}</h1>{formatted_content}'
105
+ book.add_item(epub_chapter)
106
+ epub_chapters.append(epub_chapter)
107
+
108
+ # Define Table of Contents
109
+ book.toc = (epub_chapters)
110
+
111
+ # Add default NCX and Nav files
112
+ book.add_item(epub.EpubNcx())
113
+ book.add_item(epub.EpubNav())
114
+
115
+ # Define CSS style
116
+ style = '''
117
+ @namespace epub "http://www.idpf.org/2007/ops";
118
+ body {
119
+ font-family: Cambria, Liberation Serif, serif;
120
+ }
121
+ h1 {
122
+ text-align: left;
123
+ text-transform: uppercase;
124
+ font-weight: 200;
125
+ }
126
+ '''
127
+
128
+ # Add CSS file
129
+ nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
130
+ book.add_item(nav_css)
131
+
132
+ # Create spine
133
+ book.spine = ['nav'] + epub_chapters
134
+
135
+ # 检查目录是否存在,如果不存在则创建
136
+ directory = "./epub/"
137
+ if not os.path.exists(directory):
138
+ os.makedirs(directory)
139
+
140
+ # 保存 EPUB 文件
141
+ file_path = f"./epub/{title}.epub" # 修改为您想要的文件路径
142
+ epub.write_epub(file_path, book)
143
+
144
+ return file_path
config.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+ import uuid
4
+ from dotenv import load_dotenv
5
+
6
+ from tenacity import (
7
+ retry,
8
+ stop_after_attempt,
9
+ wait_random_exponential,
10
+ ) # for exponential backoff
11
+
12
+
13
+ # 加载.env文件中的环境变量
14
+ load_dotenv()
15
+
16
+ llm_model_name = "gpt-3.5-turbo-16k"
17
+
18
+
19
+ openai.api_key = os.getenv("OPENAI_API_KEY") # get it at https://platform.openai.com/
20
+ if os.getenv("OPENAI_API_BASE"):
21
+ openai.api_base = os.getenv("OPENAI_API_BASE")
22
+ stability_api_key = os.getenv("STABILITY_API_KEY") # get it at https://beta.dreamstudio.ai/
23
+ anthropic_api_key = os.getenv("ANTHROPIC_API_KEY") # optional, if you don't add it, keep it as "YOUR ANTHROPIC API KEY"
24
+
25
+
26
+ @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
27
+ def completion_with_backoff(**kwargs):
28
+ return openai.ChatCompletion.create(**kwargs)
29
+
30
+
31
+ # 生成32位唯一的uuid
32
+ def generate_uuid():
33
+ # 生成UUID
34
+ id = uuid.uuid4().hex
35
+ return id
36
+
37
+
38
+ # 保存小说每章节的内容
39
+ def save_novel_chapter(novel_id, chapter_index, file_name, file_content):
40
+ # 创建章节文件目录
41
+ chapter_folder = os.path.join(os.getcwd(), f"story/{novel_id}/chapter_{chapter_index + 1}")
42
+ if not os.path.exists(chapter_folder):
43
+ os.makedirs(chapter_folder)
44
+
45
+ # 写入章节内容到文件
46
+ file_path = os.path.join(chapter_folder, f"{file_name}.txt")
47
+ with open(file_path, "w") as file:
48
+ file.write(file_content)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai==0.28.0
2
+ EbookLib==0.18
3
+ anthropic==0.3.11
4
+ python-dotenv==1.0.0
5
+ gradio==3.42.0
6
+ tenacity==8.2.3
run.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from write_story import write_fantasy_novel
4
+ from author import create_cover_image
5
+ from author import create_epub
6
+ from config import anthropic_api_key
7
+
8
+ if anthropic_api_key != "YOUR ANTHROPIC API KEY":
9
+ claude_true = True
10
+ else:
11
+ claude_true = False
12
+
13
+
14
+ def generate_novel(prompt, num_chapters, writing_style, model_name):
15
+ # 调用GPT和Claude API,生成小说结果
16
+ # prompt = "A kingdom hidden deep in the forest, where every tree is a portal to another world."
17
+ # num_chapters = 2
18
+ # writing_style = "Clear and easily understandable, similar to a young adult novel. Lots of dialogue."
19
+ # model_name = "gpt-3.5-turbo-16k"
20
+ if not prompt or not writing_style:
21
+ raise gr.Error("提示词和写作风格是必填项")
22
+ if num_chapters < 1:
23
+ raise gr.Error("章节数必须大于等于1")
24
+
25
+ num_chapters = int(num_chapters)
26
+ novel, title, chapters, chapter_titles = write_fantasy_novel(prompt,
27
+ num_chapters, writing_style, claude_true, model_name)
28
+
29
+ # 用chapter_titles中的正文取代章节说明
30
+ for i, chapter in enumerate(chapters):
31
+ chapter_number_and_title = list(chapter_titles[i].keys())[0]
32
+ chapter_titles[i] = {chapter_number_and_title: chapter}
33
+
34
+ # 生成小说的封面
35
+ image_url = create_cover_image(str(chapter_titles))
36
+ print(f"Image URL: {image_url}")
37
+
38
+ # 生成小说 EPUB 文件
39
+ file_url = create_epub(title, 'AI', chapter_titles, image_url)
40
+ print(f"Novel URL: {file_url}")
41
+
42
+ # novel, file_path = write_fantasy_novel(prompt, num_chapters, writing_style)
43
+ return { "image_url": image_url, "file_url": file_url }
44
+
45
+
46
+ def generate_output(prompt, num_chapters, writing_style, model_name):
47
+ try:
48
+ output = generate_novel(prompt, num_chapters, writing_style, model_name)
49
+ print(output)
50
+ return (output["image_url"], output["file_url"])
51
+ except Exception as e:
52
+ raise gr.Error({str(e)})
53
+ return f"An error occurred: {str(e)}"
54
+
55
+
56
+ inputs = [
57
+ gr.Textbox(value="一个被遗忘的小岛,上面有一座古老的灯塔。当灯塔亮起时,岛上的生物就会发生奇异的变化。", lines=2, placeholder="Usage:一个被遗忘的小岛,上面有一座古老的灯塔。当灯塔亮起时,岛上的生物就会发生奇异的变化。", label="小说提示词"),
58
+ gr.Number(value=1, label="小说章节数"),
59
+ gr.Textbox(value="紧张刺激,类似于青少年恐怖小说。有很多对话和内心独白", lines=2, placeholder="Usage:紧张刺激,类似于青少年恐怖小说。有很多对话和内心独白", label="AI写作风格"),
60
+ gr.Dropdown(["gpt-3.5-turbo-16k", "gpt-3.5-turbo", "gpt-4", "gpt-4-32k"], label="选择GPT模型", value="gpt-3.5-turbo")
61
+ ]
62
+
63
+
64
+ outputs = [
65
+ gr.Image(label="封面图片", width=1028, height=300),
66
+ gr.File(label="EPUB文件")
67
+ ]
68
+
69
+ title = "StoryGenius:一款AI自动创作小说工具"
70
+ description = "根据小说的提示词、写作风格和章节数量几分钟即可快速生成奇幻小说。并自动打包为电子书格式。"
71
+
72
+
73
+ iface = gr.Interface(fn=generate_output, inputs=inputs, outputs=outputs, title=title, description=description)
74
+ iface.launch(server_name="0.0.0.0", server_port=8000)
write_story.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import os
3
+ import requests
4
+ import ast
5
+ import time
6
+ from anthropic import Anthropic
7
+ from config import anthropic_api_key
8
+ from config import llm_model_name
9
+ from config import completion_with_backoff
10
+ from config import save_novel_chapter
11
+ from config import generate_uuid
12
+
13
+ def print_step_costs(response, model):
14
+ input = response['usage']['prompt_tokens']
15
+ output = response['usage']['completion_tokens']
16
+
17
+ if model == "gpt-4" or model == "gpt-4":
18
+ input_per_token = 0.00003
19
+ output_per_token = 0.00006
20
+ if model == "gpt-3.5-turbo-16k":
21
+ input_per_token = 0.000003
22
+ output_per_token = 0.000004
23
+ if model == "gpt-4-32k" or model == "gpt-4-32k":
24
+ input_per_token = 0.00006
25
+ output_per_token = 0.00012
26
+ if model == "gpt-3.5-turbo" or model == "gpt-3.5-turbo":
27
+ input_per_token = 0.0000015
28
+ output_per_token = 0.000002
29
+ if model == "claude-2":
30
+ input_per_token = 0.00001102
31
+ output_per_token = 0.00003268
32
+
33
+ input_cost = int(input) * input_per_token
34
+ output_cost = int(output) * output_per_token
35
+
36
+ total_cost = input_cost + output_cost
37
+ print('Step Cost (OpenAI):', total_cost)
38
+
39
+
40
+ def print_step_costs_anthropic(prompt, response):
41
+ client = Anthropic()
42
+ in_tokens = client.count_tokens(prompt)
43
+ out_tokens = client.count_tokens(response)
44
+
45
+ input_cost = 0.00001102 * in_tokens
46
+ output_cost = 0.00003268 * out_tokens
47
+
48
+ total_cost = input_cost + output_cost
49
+ print('Step Cost (Anthropic):', total_cost)
50
+
51
+
52
+ def generate_plots(prompt):
53
+ response = completion_with_backoff(
54
+ model=llm_model_name,
55
+ messages=[
56
+ {"role": "system", "content": "You are a creative assistant that generates engaging fantasy novel plots."},
57
+ {"role": "user", "content": f"Generate 10 fantasy novel plots based on this prompt: {prompt}"}
58
+ ]
59
+ )
60
+
61
+ print_step_costs(response, llm_model_name)
62
+
63
+ return response['choices'][0]['message']['content'].split('\n')
64
+
65
+
66
+ def select_most_engaging(plots):
67
+ response = completion_with_backoff(
68
+ model=llm_model_name,
69
+ messages=[
70
+ {"role": "system", "content": "You are an expert in writing fantastic fantasy novel plots."},
71
+ {"role": "user",
72
+ "content": f"Here are a number of possible plots for a new novel: "
73
+ f"{plots}\n\n--\n\nNow, write the final plot that we will go with. "
74
+ f"It can be one of these, a mix of the best elements of multiple, "
75
+ f"or something completely new and better. "
76
+ f"The most important thing is the plot should be fantastic, unique, and engaging."}
77
+ ]
78
+ )
79
+
80
+ print_step_costs(response, llm_model_name)
81
+
82
+ return response['choices'][0]['message']['content']
83
+
84
+
85
+ def improve_plot(plot):
86
+ response = completion_with_backoff(
87
+ model=llm_model_name,
88
+ messages=[
89
+ {"role": "system", "content": "You are an expert in improving and refining story plots."},
90
+ {"role": "user", "content": f"Improve this plot: {plot}"}
91
+ ]
92
+ )
93
+
94
+ print_step_costs(response, llm_model_name)
95
+
96
+ return response['choices'][0]['message']['content']
97
+
98
+
99
+ def get_title(plot):
100
+ response = completion_with_backoff(
101
+ model=llm_model_name,
102
+ messages=[
103
+ {"role": "system", "content": "You are an expert writer."},
104
+ {"role": "user",
105
+ "content": f"Here is the plot: {plot}\n\nWhat is the title of this book? "
106
+ f"Just respond with the title, do nothing else. Please respond in Chinese."}
107
+ ]
108
+ )
109
+
110
+ print_step_costs(response, llm_model_name)
111
+
112
+ return response['choices'][0]['message']['content']
113
+
114
+
115
+ def write_first_chapter(plot, first_chapter_title, writing_style, claude=True):
116
+ if claude:
117
+ url = "https://api.anthropic.com/v1/complete"
118
+
119
+ headers = {
120
+ "anthropic-version": "2023-06-01",
121
+ "content-type": "application/json",
122
+ "x-api-key": anthropic_api_key,
123
+ }
124
+
125
+ prompt_one = f"\n\nHuman: You are a world-class fantasy writer. " \
126
+ f"I will give you the title of a novel, a high-level plot to follow, " \
127
+ f"and a desired writing style to use. " \
128
+ f"From the title, plot, and writing style, write the first chapter of the novel. " \
129
+ f"Make it incredibly unique, engaging, and well-written. " \
130
+ f"Start it off with a bang, and include dialogue. " \
131
+ f"Include only the chapter text, and no surrounding explanations or text. " \
132
+ f"Do you understand?\n\nAssistant: Yes, I understand. " \
133
+ f"Please provide the title, plot, and writing style, " \
134
+ f"and I will write a fantastic opening chapter with dialogue that will hook the reader." \
135
+ f"\n\nHuman: Here is the high-level plot to follow: {plot}" \
136
+ f"\n\nThe title of the novel is: `{first_chapter_title}`.\n\n" \
137
+ f"Here is a description of the writing style you should use: `{writing_style}`" \
138
+ f"\n\nWrite the first chapter please!\n\nAssistant: " \
139
+ f"Okay, I've got a really exciting first chapter for you. " \
140
+ f"It's twenty paragraphs long and very well-written. " \
141
+ f"As you can see, the language I use is very understandable — " \
142
+ f"I avoided using overly complex words and phrases. Please respond in Chinese:" \
143
+ f"\n\nTitle: {first_chapter_title}\n\nChapter #1 Text```"
144
+
145
+ data = {
146
+ "model": "claude-2",
147
+ "prompt": prompt_one,
148
+ "max_tokens_to_sample": 5000,
149
+ }
150
+
151
+ response = requests.post(url, headers=headers, json=data)
152
+
153
+ initial_first_chapter = response.json()['completion'].strip().split('```')[0].strip()
154
+
155
+ print_step_costs_anthropic(prompt_one, response.json()['completion'])
156
+
157
+ prompt_two = f"\n\nHuman: You are a world-class fantasy writer. " \
158
+ f"Your job is to take your student's rough initial draft of the first chapter of their fantasy novel, " \
159
+ f"and rewrite it to be significantly better, with much more detail. " \
160
+ f"Do you understand?\n\nAssistant: Yes, I understand. " \
161
+ f"Please provide the plot and the student-written chapter, " \
162
+ f"and I will rewrite the chapter in a far superior way.\n\nHuman: " \
163
+ f"Here is the high-level plot you asked your student to follow: " \
164
+ f"{plot}\n\nHere is the first chapter they wrote: {initial_first_chapter}\n\n" \
165
+ f"Now, rewrite the first chapter of this novel, in a way that is far superior to your student's chapter. " \
166
+ f"It should still follow the exact same plot, but it should be far more detailed, much longer, and more engaging. " \
167
+ f"Here is a description of the writing style you should use: `{writing_style}`\n\nAssistant: Okay, I've rewritten the first chapter. " \
168
+ f"I took great care to improve it. While the plot is the same, " \
169
+ f"you can see that my version is noticeably longer, easier to read, " \
170
+ f"and more exciting. Also, the language I used is far more accessible to a broader audience." \
171
+ f"Please respond in Chinese.\n\n```"
172
+ data = {
173
+ "model": "claude-2",
174
+ "prompt": prompt_two,
175
+ "max_tokens_to_sample": 5000,
176
+ }
177
+
178
+ response_improved = requests.post(url, headers=headers, json=data)
179
+
180
+ print_step_costs_anthropic(prompt_two, response_improved.json()['completion'])
181
+
182
+ return response_improved.json()['completion'].strip().split('```')[0].strip()
183
+
184
+
185
+ else:
186
+ response = completion_with_backoff(
187
+ model=llm_model_name,
188
+ messages=[
189
+ {"role": "system", "content": "You are a world-class fantasy writer."},
190
+ {"role": "user",
191
+ "content": f"Here is the high-level plot to follow: {plot}\n\nWrite the first chapter of this novel: `{first_chapter_title}`.\n\nMake it incredibly unique, engaging, and well-written.\n\nHere is a description of the writing style you should use: `{writing_style}`\n\nInclude only the chapter text. There is no need to rewrite the chapter name. Please respond in Chinese."}
192
+ ]
193
+ )
194
+
195
+ print_step_costs(response, llm_model_name)
196
+
197
+ improved_response = completion_with_backoff(
198
+ model=llm_model_name,
199
+ messages=[
200
+ {"role": "system",
201
+ "content": "You are a world-class fantasy writer. Your job is to take your student's rough initial draft of the first chapter of their fantasy novel, and rewrite it to be significantly better, with much more detail."},
202
+ {"role": "user",
203
+ "content": f"Here is the high-level plot you asked your student to follow: {plot}\n\nHere is the first chapter they wrote: {response['choices'][0]['message']['content']}\n\nNow, rewrite the first chapter of this novel, in a way that is far superior to your student's chapter. It should still follow the exact same plot, but it should be far more detailed, much longer, and more engaging. Here is a description of the writing style you should use: `{writing_style}`.Please respond in Chinese."}
204
+ ]
205
+ )
206
+
207
+ print_step_costs(response, llm_model_name)
208
+
209
+ return improved_response['choices'][0]['message']['content']
210
+
211
+
212
+ def write_chapter(previous_chapters, plot, chapter_title, claude=True):
213
+ if claude:
214
+ url = "https://api.anthropic.com/v1/complete"
215
+
216
+ headers = {
217
+ "anthropic-version": "2023-06-01",
218
+ "content-type": "application/json",
219
+ "x-api-key": anthropic_api_key,
220
+ }
221
+
222
+ prompt = f"\n\nHuman: You are a world-class fantasy writer. I will provide you with the plot of the novel, the previous chapters, and the plan for the next chapter. Your task is to write the next chapter of the novel in Chinese, following the plot and taking in the previous chapters as context. Do you understand?\n\nAssistant: Yes, I understand. You want me to write the next chapter of a novel, using the plot you provide, the previous chapters for context, and a specific plan for the next chapter. I will ensure the chapter is beautifully written and I will not rewrite the chapter name.\n\nHuman: That's correct. Here is the plot: {plot}\n\nHere are the previous chapters: {previous_chapters}\n\nHere is the plan for the next chapter: {chapter_title}\n\nWrite it beautifully. Include only the chapter text. There is no need to rewrite the chapter name.\n\nAssistant: Here is the next chapter. As you can see, it's around the same length as the previous chapters, and contains witty dialogue:\n```Chapter"
223
+
224
+ data = {
225
+ "model": "claude-2",
226
+ "prompt": prompt,
227
+ "max_tokens_to_sample": 5000,
228
+ }
229
+
230
+ response = requests.post(url, headers=headers, json=data)
231
+
232
+ print_step_costs_anthropic(prompt, response.json()['completion'])
233
+
234
+ return 'Chapter ' + response.json()['completion'].strip().split('```')[0].strip()
235
+ else:
236
+ try:
237
+ i = random.randint(1, 2242)
238
+ response = completion_with_backoff(
239
+ model=llm_model_name,
240
+ messages=[
241
+ {"role": "system", "content": "You are a world-class fantasy writer. "},
242
+ {"role": "user",
243
+ "content": f"Plot: {plot}, Previous Chapters: {previous_chapters}\n\n--\n\nWrite the next chapter of this novel in Chinese, following the plot and taking in the previous chapters as context. Here is the plan for this chapter: {chapter_title}\n\nWrite it beautifully. Include only the chapter text. There is no need to rewrite the chapter name."}
244
+ ]
245
+ )
246
+
247
+ print_step_costs(response, llm_model_name)
248
+
249
+ return response['choices'][0]['message']['content']
250
+ except:
251
+ response = completion_with_backoff(
252
+ model=llm_model_name,
253
+ messages=[
254
+ {"role": "system", "content": "You are a world-class fantasy writer."},
255
+ {"role": "user",
256
+ "content": f"Plot: {plot}, Previous Chapters: {previous_chapters}\n\n--\n\nWrite the next chapter of this novel in Chinese, following the plot and taking in the previous chapters as context. Here is the plan for this chapter: {chapter_title}\n\nWrite it beautifully. Include only the chapter text. There is no need to rewrite the chapter name."}
257
+ ]
258
+ )
259
+
260
+ print_step_costs(response, llm_model_name)
261
+
262
+ return response['choices'][0]['message']['content']
263
+
264
+
265
+ def generate_storyline(prompt, num_chapters):
266
+ print("Generating storyline with chapters and high-level details...")
267
+ json_format = """[{"Chapter CHAPTER_NUMBER_HERE - CHAPTER_TITLE_GOES_HERE":
268
+ "CHAPTER_OVERVIEW_AND_DETAILS_GOES_HERE"}, ...]"""
269
+ response = completion_with_backoff(
270
+ model=llm_model_name,
271
+ messages=[
272
+ {"role": "system",
273
+ "content": "You are a world-class fantasy writer. Your job is to write a detailed storyline,"
274
+ " complete with chapters, for a fantasy novel. "
275
+ "Don't be flowery -- you want to get the message across in as few words as possible. "
276
+ "But those words should contain lots of information. Please respond in Chinese"},
277
+ {"role": "user",
278
+ "content": f'Write a fantastic storyline with {num_chapters} chapters and high-level details based on this plot:'
279
+ f' {prompt}.\n\nDo it in this list of dictionaries format {json_format}.'
280
+ f' And Please respond in Chinese. The response content must be in standard JSON format, without any prefixes and special symbols.'}
281
+ ]
282
+ )
283
+
284
+ print_step_costs(response, llm_model_name)
285
+
286
+ improved_response = completion_with_backoff(
287
+ model=llm_model_name,
288
+ messages=[
289
+ {"role": "system",
290
+ "content": "You are a world-class fantasy writer. "
291
+ "Your job is to take your student's rough initial draft of the storyline of a fantasy novel in Chinese, "
292
+ "and rewrite it to be significantly better. Please respond in Chinese"},
293
+ {"role": "user",
294
+ "content": f"Here is the draft storyline they wrote: {response['choices'][0]['message']['content']}\n\nNow, "
295
+ f"rewrite the storyline in Chinese, in a way that is far superior to your student's version. "
296
+ f"It should have the same number of chapters, "
297
+ f"but it should be much improved in as many ways as possible. "
298
+ f"Remember to do it in this list of dictionaries format {json_format}. please respond in Chinese"
299
+ f' And please, only return the JSON content without any prefix.'}
300
+ ]
301
+ )
302
+
303
+ print_step_costs(improved_response, llm_model_name)
304
+
305
+ return improved_response['choices'][0]['message']['content']
306
+
307
+
308
+ def write_to_file(prompt, content):
309
+ # Create a directory for the prompts if it doesn't exist
310
+ if not os.path.exists('prompts'):
311
+ os.mkdir('prompts')
312
+
313
+ # Replace invalid characters for filenames
314
+ valid_filename = ''.join(c for c in prompt if c.isalnum() or c in (' ', '.', '_')).rstrip()
315
+ file_path = f'prompts/{valid_filename}.txt'
316
+
317
+ with open(file_path, 'w', encoding='utf-8') as f:
318
+ f.write(content)
319
+
320
+ print(f'Output for prompt "{prompt}" has been written to {file_path}\n')
321
+
322
+
323
+ def write_fantasy_novel(prompt, num_chapters, writing_style, claude_true=False, model_name="gpt-3.5-turbo-16k"):
324
+ global llm_model_name
325
+ llm_model_name = model_name
326
+
327
+ # 每本小说生成一个唯一的uuid
328
+ novel_id = generate_uuid()
329
+
330
+ plots = generate_plots(prompt)
331
+ print('generated plots')
332
+ print(f'【plots】: {plots}\n\n')
333
+
334
+ best_plot = select_most_engaging(plots)
335
+ print('selected best plot')
336
+ print(f'【best_plot】: {best_plot}\n\n')
337
+
338
+ improved_plot = improve_plot(best_plot)
339
+ print('plot improved')
340
+ print(f'【improved_plot】: {improved_plot}\n\n')
341
+ time.sleep(20)
342
+
343
+ title = get_title(improved_plot)
344
+ print('title generated')
345
+ print(f'【title】: {title}\n\n')
346
+
347
+ storyline = generate_storyline(improved_plot, num_chapters)
348
+ print('storyline generated')
349
+ print(f'【storyline】: {storyline}\n\n')
350
+
351
+ chapter_titles = ast.literal_eval(storyline)
352
+ print(f'【chapter_titles】: {chapter_titles}\n\n')
353
+
354
+ novel = f"Storyline:\n{storyline}\n\n"
355
+
356
+ first_chapter = write_first_chapter(storyline, chapter_titles[0], writing_style.strip(), claude_true)
357
+ print('first chapter written')
358
+ save_novel_chapter(novel_id, 0, list(chapter_titles[0])[0], first_chapter)
359
+ print(f'【first_chapter】: {first_chapter}\n\n')
360
+ time.sleep(20)
361
+
362
+ novel += f"Chapter 1:\n{first_chapter}\n"
363
+ chapters = [first_chapter]
364
+
365
+ for i in range(num_chapters - 1):
366
+ print(f"Writing chapter {i + 2}...") # + 2 because the first chapter was already added
367
+ time.sleep(30)
368
+
369
+ chapter = write_chapter(novel, storyline, chapter_titles[i + 1], claude_true)
370
+ try:
371
+ if len(str(chapter)) < 100:
372
+ time.sleep(30)
373
+ print('Length minimum not hit. Trying again.')
374
+ chapter = write_chapter(novel, storyline, chapter_titles[i + 1], claude_true)
375
+ except:
376
+ time.sleep(20)
377
+ chapter = write_chapter(novel, storyline, chapter_titles[i + 1], claude_true)
378
+
379
+ novel += f"Chapter {i + 2}:\n{chapter}\n"
380
+ chapters.append(chapter)
381
+ print(f'【Chapter_{i + 2}】: {chapter}\n\n')
382
+ save_novel_chapter(novel_id, (i+1), list(chapter_titles[i + 1])[0], chapter)
383
+
384
+ return novel, title, chapters, chapter_titles