rodrigomasini commited on
Commit
123218a
·
verified ·
1 Parent(s): c56fbba

Create modified_version.py

Browse files
Files changed (1) hide show
  1. archives/modified_version.py +276 -0
archives/modified_version.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ from recurrentgpt import RecurrentGPT
4
+ from human_simulator import Human
5
+ from sentence_transformers import SentenceTransformer
6
+ from utils import get_init, parse_instructions
7
+ import re
8
+
9
+ # from urllib.parse import quote_plus
10
+ # from pymongo import MongoClient
11
+
12
+ # uri = "mongodb://%s:%s@%s" % (quote_plus("xxx"),
13
+ # quote_plus("xxx"), "localhost")
14
+ # client = MongoClient(uri, maxPoolSize=None)
15
+ # db = client.recurrentGPT_db
16
+ # log = db.log
17
+
18
+ _CACHE = {}
19
+
20
+
21
+ # Build the semantic search model
22
+ embedder = SentenceTransformer('multi-qa-mpnet-base-cos-v1')
23
+
24
+ def init_prompt(novel_type, description):
25
+ if description == "":
26
+ description = ""
27
+ else:
28
+ description = " about " + description
29
+ return f"""
30
+ Please write a {novel_type} novel{description} with 50 chapters. Follow the format below precisely:
31
+ Begin with the name of the novel.
32
+ Next, write an outline for the first chapter. The outline should describe the background and the beginning of the novel.
33
+ Write the first three paragraphs with their indication of the novel based on your outline. Write in a novelistic style and take your time to set the scene.
34
+ Write a summary that captures the key information of the three paragraphs.
35
+ Finally, write three different instructions for what to write next, each containing around five sentences. Each instruction should present a possible, interesting continuation of the story.
36
+ The output format should follow these guidelines:
37
+ Name: <name of the novel>
38
+ Outline: <outline for the first chapter>
39
+ Paragraph 1: <content for paragraph 1>
40
+ Paragraph 2: <content for paragraph 2>
41
+ Paragraph 3: <content for paragraph 3>
42
+ Summary: <content of summary>
43
+ Instruction 1: <content for instruction 1>
44
+ Instruction 2: <content for instruction 2>
45
+ Instruction 3: <content for instruction 3>
46
+ Make sure to be precise and follow the output format strictly.
47
+ """
48
+
49
+ def init(novel_type, description, request: gr.Request):
50
+ if novel_type == "":
51
+ novel_type = "Science Fiction"
52
+ global _CACHE
53
+ cookie = request.headers['cookie']
54
+ cookie = cookie.split('; _gat_gtag')[0]
55
+ # prepare first init
56
+ init_paragraphs = get_init(text=init_prompt(novel_type,description))
57
+ # print(init_paragraphs)
58
+ start_input_to_human = {
59
+ 'output_paragraph': init_paragraphs['Paragraph 3'],
60
+ 'input_paragraph': '\n\n'.join([init_paragraphs['Paragraph 1'], init_paragraphs['Paragraph 2']]),
61
+ 'output_memory': init_paragraphs['Summary'],
62
+ "output_instruction": [init_paragraphs['Instruction 1'], init_paragraphs['Instruction 2'], init_paragraphs['Instruction 3']]
63
+ }
64
+
65
+ _CACHE[cookie] = {"start_input_to_human": start_input_to_human,
66
+ "init_paragraphs": init_paragraphs}
67
+ written_paras = f"""Title: {init_paragraphs['name']}
68
+ Outline: {init_paragraphs['Outline']}
69
+ Paragraphs:
70
+ {start_input_to_human['input_paragraph']}"""
71
+ long_memory = parse_instructions([init_paragraphs['Paragraph 1'], init_paragraphs['Paragraph 2']])
72
+ # short memory, long memory, current written paragraphs, 3 next instructions
73
+ return start_input_to_human['output_memory'], long_memory, written_paras, init_paragraphs['Instruction 1'], init_paragraphs['Instruction 2'], init_paragraphs['Instruction 3']
74
+
75
+ def step(short_memory, long_memory, instruction1, instruction2, instruction3, current_paras, request: gr.Request, ):
76
+ if current_paras == "":
77
+ return "", "", "", "", "", ""
78
+ global _CACHE
79
+ # print(list(_CACHE.keys()))
80
+ # print(request.headers.get('cookie'))
81
+ cookie = request.headers['cookie']
82
+ cookie = cookie.split('; _gat_gtag')[0]
83
+ cache = _CACHE[cookie]
84
+
85
+ if "writer" not in cache:
86
+ start_input_to_human = cache["start_input_to_human"]
87
+ start_input_to_human['output_instruction'] = [
88
+ instruction1, instruction2, instruction3]
89
+ init_paragraphs = cache["init_paragraphs"]
90
+ human = Human(input=start_input_to_human,
91
+ memory=None, embedder=embedder)
92
+ human.step()
93
+ start_short_memory = init_paragraphs['Summary']
94
+ writer_start_input = human.output
95
+
96
+ # Init writerGPT
97
+ writer = RecurrentGPT(input=writer_start_input, short_memory=start_short_memory, long_memory=[
98
+ init_paragraphs['Paragraph 1'], init_paragraphs['Paragraph 2']], memory_index=None, embedder=embedder)
99
+ cache["writer"] = writer
100
+ cache["human"] = human
101
+ writer.step()
102
+ else:
103
+ human = cache["human"]
104
+ writer = cache["writer"]
105
+ output = writer.output
106
+ output['output_memory'] = short_memory
107
+ #randomly select one instruction out of three
108
+ instruction_index = random.randint(0,2)
109
+ output['output_instruction'] = [instruction1, instruction2, instruction3][instruction_index]
110
+ human.input = output
111
+ human.step()
112
+ writer.input = human.output
113
+ writer.step()
114
+
115
+ long_memory = [[v] for v in writer.long_memory]
116
+ # short memory, long memory, current written paragraphs, 3 next instructions
117
+ return writer.output['output_memory'], long_memory, current_paras + '\n\n' + writer.output['input_paragraph'], human.output['output_instruction'], *writer.output['output_instruction']
118
+
119
+
120
+ def controled_step(short_memory, long_memory, selected_instruction, current_paras, request: gr.Request, ):
121
+ if current_paras == "":
122
+ return "", "", "", "", "", ""
123
+ global _CACHE
124
+ # print(list(_CACHE.keys()))
125
+ # print(request.headers.get('cookie'))
126
+ cookie = request.headers['cookie']
127
+ cookie = cookie.split('; _gat_gtag')[0]
128
+ cache = _CACHE[cookie]
129
+ if "writer" not in cache:
130
+ start_input_to_human = cache["start_input_to_human"]
131
+ start_input_to_human['output_instruction'] = selected_instruction
132
+ init_paragraphs = cache["init_paragraphs"]
133
+ human = Human(input=start_input_to_human,
134
+ memory=None, embedder=embedder)
135
+ human.step()
136
+ start_short_memory = init_paragraphs['Summary']
137
+ writer_start_input = human.output
138
+
139
+ # Init writerGPT
140
+ writer = RecurrentGPT(input=writer_start_input, short_memory=start_short_memory, long_memory=[
141
+ init_paragraphs['Paragraph 1'], init_paragraphs['Paragraph 2']], memory_index=None, embedder=embedder)
142
+ cache["writer"] = writer
143
+ cache["human"] = human
144
+ writer.step()
145
+ else:
146
+ human = cache["human"]
147
+ writer = cache["writer"]
148
+ output = writer.output
149
+ output['output_memory'] = short_memory
150
+ output['output_instruction'] = selected_instruction
151
+ human.input = output
152
+ human.step()
153
+ writer.input = human.output
154
+ writer.step()
155
+
156
+ # short memory, long memory, current written paragraphs, 3 next instructions
157
+ return writer.output['output_memory'], parse_instructions(writer.long_memory), current_paras + '\n\n' + writer.output['input_paragraph'], *writer.output['output_instruction']
158
+
159
+
160
+ # SelectData is a subclass of EventData
161
+ def on_select(instruction1, instruction2, instruction3, evt: gr.SelectData):
162
+ selected_plan = int(evt.value.replace("Instruction ", ""))
163
+ selected_plan = [instruction1, instruction2, instruction3][selected_plan-1]
164
+ return selected_plan
165
+
166
+
167
+ with gr.Blocks(title="RecurrentGPT", css="footer {visibility: hidden}", theme='sudeepshouche/minimalist') as demo:
168
+ gr.Markdown(
169
+ """
170
+ # RecurrentGPT
171
+ Interactive Generation of (Arbitrarily) Long Texts with Human-in-the-Loop
172
+ """)
173
+ with gr.Tab("Auto-Generation"):
174
+ with gr.Row():
175
+ with gr.Column():
176
+ with gr.Box():
177
+ with gr.Row():
178
+ with gr.Column(scale=1, min_width=200):
179
+ novel_type = gr.Textbox(
180
+ label="Novel Type", placeholder="e.g. science fiction")
181
+ with gr.Column(scale=2, min_width=400):
182
+ description = gr.Textbox(label="Description")
183
+ btn_init = gr.Button(
184
+ "Init Novel Generation", variant="primary")
185
+ gr.Examples(["Science Fiction", "Romance", "Mystery", "Fantasy",
186
+ "Historical", "Horror", "Thriller", "Western", "Young Adult", ], inputs=[novel_type])
187
+ written_paras = gr.Textbox(
188
+ label="Written Paragraphs (editable)", max_lines=21, lines=21)
189
+ with gr.Column():
190
+ with gr.Box():
191
+ gr.Markdown("### Memory Module\n")
192
+ short_memory = gr.Textbox(
193
+ label="Short-Term Memory (editable)", max_lines=3, lines=3)
194
+ long_memory = gr.Textbox(
195
+ label="Long-Term Memory (editable)", max_lines=6, lines=6)
196
+ # long_memory = gr.Dataframe(
197
+ # # label="Long-Term Memory (editable)",
198
+ # headers=["Long-Term Memory (editable)"],
199
+ # datatype=["str"],
200
+ # row_count=3,
201
+ # max_rows=3,
202
+ # col_count=(1, "fixed"),
203
+ # type="array",
204
+ # )
205
+ with gr.Box():
206
+ gr.Markdown("### Instruction Module\n")
207
+ with gr.Row():
208
+ instruction1 = gr.Textbox(
209
+ label="Instruction 1 (editable)", max_lines=4, lines=4)
210
+ instruction2 = gr.Textbox(
211
+ label="Instruction 2 (editable)", max_lines=4, lines=4)
212
+ instruction3 = gr.Textbox(
213
+ label="Instruction 3 (editable)", max_lines=4, lines=4)
214
+ selected_plan = gr.Textbox(
215
+ label="Revised Instruction (from last step)", max_lines=2, lines=2)
216
+
217
+ btn_step = gr.Button("Next Step", variant="primary")
218
+
219
+ btn_init.click(init, inputs=[novel_type, description], outputs=[
220
+ short_memory, long_memory, written_paras, instruction1, instruction2, instruction3])
221
+ btn_step.click(step, inputs=[short_memory, long_memory, instruction1, instruction2, instruction3, written_paras], outputs=[
222
+ short_memory, long_memory, written_paras, selected_plan, instruction1, instruction2, instruction3])
223
+
224
+ with gr.Tab("Human-in-the-Loop"):
225
+ with gr.Row():
226
+ with gr.Column():
227
+ with gr.Box():
228
+ with gr.Row():
229
+ with gr.Column(scale=1, min_width=200):
230
+ novel_type = gr.Textbox(
231
+ label="Novel Type", placeholder="e.g. science fiction")
232
+ with gr.Column(scale=2, min_width=400):
233
+ description = gr.Textbox(label="Description")
234
+ btn_init = gr.Button(
235
+ "Init Novel Generation", variant="primary")
236
+ gr.Examples(["Science Fiction", "Romance", "Mystery", "Fantasy",
237
+ "Historical", "Horror", "Thriller", "Western", "Young Adult", ], inputs=[novel_type])
238
+ written_paras = gr.Textbox(
239
+ label="Written Paragraphs (editable)", max_lines=23, lines=23)
240
+ with gr.Column():
241
+ with gr.Box():
242
+ gr.Markdown("### Memory Module\n")
243
+ short_memory = gr.Textbox(
244
+ label="Short-Term Memory (editable)", max_lines=3, lines=3)
245
+ long_memory = gr.Textbox(
246
+ label="Long-Term Memory (editable)", max_lines=6, lines=6)
247
+ with gr.Box():
248
+ gr.Markdown("### Instruction Module\n")
249
+ with gr.Row():
250
+ instruction1 = gr.Textbox(
251
+ label="Instruction 1", max_lines=3, lines=3, interactive=False)
252
+ instruction2 = gr.Textbox(
253
+ label="Instruction 2", max_lines=3, lines=3, interactive=False)
254
+ instruction3 = gr.Textbox(
255
+ label="Instruction 3", max_lines=3, lines=3, interactive=False)
256
+ with gr.Row():
257
+ with gr.Column(scale=1, min_width=100):
258
+ selected_plan = gr.Radio(["Instruction 1", "Instruction 2", "Instruction 3"], label="Instruction Selection",)
259
+ # info="Select the instruction you want to revise and use for the next step generation.")
260
+ with gr.Column(scale=3, min_width=300):
261
+ selected_instruction = gr.Textbox(
262
+ label="Selected Instruction (editable)", max_lines=5, lines=5)
263
+
264
+ btn_step = gr.Button("Next Step", variant="primary")
265
+
266
+ btn_init.click(init, inputs=[novel_type, description], outputs=[
267
+ short_memory, long_memory, written_paras, instruction1, instruction2, instruction3])
268
+ btn_step.click(controled_step, inputs=[short_memory, long_memory, selected_instruction, written_paras], outputs=[
269
+ short_memory, long_memory, written_paras, instruction1, instruction2, instruction3])
270
+ selected_plan.select(on_select, inputs=[
271
+ instruction1, instruction2, instruction3], outputs=[selected_instruction])
272
+
273
+ demo.queue(concurrency_count=1)
274
+
275
+ if __name__ == "__main__":
276
+ demo.launch()