rodrigomasini commited on
Commit
7747457
·
1 Parent(s): 4dad84d

Create gradio_server.py

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