File size: 14,832 Bytes
65642c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f178e59
65642c3
 
 
 
 
 
f178e59
 
 
 
 
 
 
 
 
 
 
65642c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f178e59
65642c3
 
 
 
 
 
 
f178e59
65642c3
 
 
 
 
 
 
 
f178e59
 
 
 
 
 
 
 
 
65642c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f178e59
 
 
 
 
 
 
 
 
 
65642c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f178e59
 
 
65642c3
 
 
f178e59
 
 
 
 
 
65642c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f178e59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import os.path
import gradio as gr
import numpy as np
import asyncio
import shutil

import src.control.control as control


"""
==================================
A. Component part
==================================
"""

with gr.Blocks() as gptdoc:
    with gr.Row():

        with gr.Column():
            pass

        with gr.Column(scale=10):

            gr.Markdown("# GPTdoc")
            gr.Markdown ("Master your sources when generating your documents")
            gr.Markdown("### 1. You define the plan of your document ")
            gr.Markdown("### 2. You select the sources for the text generation: from public unkown sources,"
                        " from wikipedia, or from your own files")
            gr.Markdown("### 3. You launch the text generation and, when it is ready, "
                        "you can download the generated text")
            gr.Markdown("\n\n\n")


            """
            1. input docs components
            """

            gr.Markdown("# 1. Define the plan of your document")

            f = open('data/usage.txt', 'r')
            usage = f.read()

            input_text = gr.Textbox(
                label="enter your text",
                lines=25,
                max_lines=25,
                interactive=True,
                elem_classes="selected_",
                placeholder=usage,
            )

            with gr.Row():
                upload_btn = gr.UploadButton(type='file')
                example1 = gr.Button("One task example")
                example2 = gr.Button("Several tasks example")

            """
            2. source components
            """

            gr.Markdown("# 2. Choose the sources for the document generation")

            with gr.Column(visible=True, variant='panel') as select_col:
                gr.Markdown("### Select the sources")
                source_radio = gr.Radio(
                    choices=["Unknown sources", "My own sources"],
                    label="",
                    value="Unknown sources",
                    visible=True,
                )

            with gr.Column(visible=False, variant='panel') as db_col:
                gr.Markdown("### My sources")
                db_list_comp = gr.CheckboxGroup(
                    label="Current content",
                    info="These documents are currently your sources. Unselect the documents you don't want to be taken"
                         "into account when generating the document",
                    visible=True,
                    interactive=True,
                )
                with gr.Row():
                    db_reset_btn = gr.Button("Reset the sources", visible=False).style(full_width=False, size="sm")
                    db_add_doc_btn = gr.Button("Add new documents", visible=True).style(full_width=False, size="sm")

            with gr.Column(visible=False, variant="panel") as add_col:
                gr.Markdown("### Add new documents      ")

                with gr.Tab("From Wikipedia"):
                    wiki_fetch_btn = gr.Button("Search for Wikipedia pages", visible=True)
                    wiki_fetch_btn.style(full_width=False, size="sm")
                    wiki_list_comp = gr.CheckboxGroup(
                        label="Select the wiki pages",
                        info="The selected pages can be added to sources",
                        visible=False,
                        interactive=True,
                    )

                    wiki_add_to_db_btn = gr.Button("Add selection to sources", visible=False)
                    wiki_add_to_db_btn.style(full_width=False, size="sm")

                with gr.Tab("From disk"):
                    my_files_list_comp = gr.Files(
                        label="Upload  own documents",
                        info="Your selected documents provide the content for generating the output document",
                        visible=True,
                    )
                    my_files_add_to_db_btn = gr.Button("Add files to sources", visible=False)
                    my_files_add_to_db_btn.style(full_width=False, size="sm")

                add_close_btn = gr.Button("Close").style(size='sm', full_width=False)

            """
            3. Generate (and inspect the document)
            """

            gr.Markdown("# 3. Generate the document")

            generate_btn = gr.Button("Generate", interactive=True)

            output_text = gr.Textbox(
                label="Generated document",
                value="",
                lines=25,
                max_lines=25,
                interactive=False,
            )

            generated_file = gr.File(
                interactive=False,
                visible=False,
            )

        with gr.Column():
            pass

    """
    ==================================
    B. Logic part
    ==================================
    """

    """
    B.1 Input text
    """
    def upload_input_file(file_):
        return upload_file(file_.name)


    def upload_example_file(btn, input_id_):
        filename = "onetask_example.txt" if btn == "One task example" else "long_example.txt"
        long_id = control.get_long_id(input_id_)
        os.mkdir('tmp_input/' + long_id)
        copypath = 'tmp_input/' + long_id + '/' + filename
        shutil.copy("data/" + filename, copypath)
        update_ = upload_file(copypath)
        update_[input_id] = gr.update(value=long_id)
        return update_


    def upload_file(filename):
        f_ = open(filename, "r")
        input_text_ = f_.read()
        update_ = {
            input_text: gr.update(value=input_text_)
        }
        return update_


    input_id = gr.State(-1)

    upload_btn.upload(upload_input_file, inputs=[upload_btn], outputs=[input_text])
    example1.click(upload_example_file, inputs=[example1, input_id], outputs=[input_text, input_id])
    example2.click(upload_example_file, inputs=[example2, input_id], outputs=[input_text, input_id])

    """
    --------------------
    B.2 Logic for sources
    --------------------
    """


    def source1_fn(source_, db_collection_):
        """
        Allows to choose the sources for the doc generation
        """
        if source_ == "My own sources":
            long_id = control.get_long_id(db_collection_)
            update_ = {
                db_collection_var: long_id,
                db_col: gr.update(visible=True),
            }
        else:
            update_ = {
                db_col: gr.update(visible=False),
            }
        return update_


    def source2_fn(db_collection_):
        """
        Allows to choose the sources for the doc generation
        """
        long_id = control.get_long_id(db_collection_)
        control.get_or_create_collection(long_id)



    def db_reset_fn(wiki_source_, db_collection_):
        """
        resets the source db
        """
        coll = control.get_or_create_collection(db_collection_)
        control.reset_collection(coll)
        wiki_to_add_not_empty = 0 < len(wiki_source_)
        update_ = {
            wiki_db_var: [],
            my_files_db_var: [],
            db_reset_btn: gr.update(visible=False),
            db_list_comp: gr.update(value=[], choices=[]),
            wiki_list_comp: gr.update(value=wiki_source_, choices=wiki_source_),
            wiki_add_to_db_btn: gr.update(visible=wiki_to_add_not_empty),
        }
        return update_


    def db_add_doc_fn():
        """
        opens the component which allows to add new own files or wiki to the source db
        """
        update_ = {
            db_add_doc_btn: gr.update(visible=False),
            add_col: gr.update(visible=True),
        }
        return update_


    def add_close_fn():
        """
        close the component which allows to add new own files or wiki to the source db
        """
        update_ = {
            db_add_doc_btn: gr.update(visible=True),
            add_col: gr.update(visible=False),
        }
        return update_


    def wiki_fetch1_fn():
        """
        fetch the wikifiles interesting for solving the tasks as defined in the input doc
        """
        update_ = {
            wiki_list_comp: gr.update(visible=True),
        }
        return update_

    def wiki_fetch2_fn(wiki_db_files_, input_text_):
        """
        fetch the wikifiles interesting for solving the tasks as defined in the input doc
        """
        wiki_interesting_files = control.wiki_fetch(input_text_)
        wiki_files = [wiki for wiki in wiki_interesting_files if wiki not in wiki_db_files_]
        update_ = {
            wiki_list_comp: gr.update(visible=True, value=wiki_files, choices=wiki_files),
            wiki_add_to_db_btn: gr.update(visible=True),
            wiki_source_var: wiki_interesting_files,
        }
        return update_


    async def wiki_add_to_db_fn(wiki_list_, wiki_source_, wiki_db_, db_list_, db_collection_):
        """
        adds the wikipages to the db source
        """
        wiki_to_add = [wiki for wiki in wiki_list_ if wiki not in wiki_db_]
        db_list_ += wiki_to_add
        wiki_db_ += wiki_to_add
        wiki_source_remaining = [wiki for wiki in wiki_source_ if wiki not in wiki_db_]
        tasks = [control.wiki_upload_and_store(wiki, db_collection_) for wiki in wiki_to_add]
        await asyncio.gather(*tasks)
        db_not_empty = 0 < len(db_list_)
        wiki_to_add_not_empty = 0 < len(wiki_source_remaining)
        update_ = {
            wiki_db_var: wiki_db_,
            wiki_list_comp: gr.update(value=wiki_source_remaining, choices=wiki_source_remaining),
            wiki_add_to_db_btn: gr.update(visible=wiki_to_add_not_empty),
            db_list_comp: gr.update(
                visible=True,
                value=db_list_,
                choices=db_list_,
                label="Database content"),
            db_reset_btn: gr.update(visible=db_not_empty),
            generate_btn: gr.update(visible=True, interactive=db_not_empty),
        }
        return update_


    def my_files_list_fn(my_files_list_):

        update_ = {
            my_files_add_to_db_btn: gr.update(visible=bool(my_files_list_))
        }
        return update_


    async def my_files_add_to_db_fn(my_files_list_, my_files_db_, db_list_):
        """
        adds the files to the db source
        """
        my_files_to_add = [fi.name for fi in my_files_list_ if fi.name not in my_files_db_]
        tasks = [control.my_files_upload_and_store(f_name) for f_name in my_files_to_add]
        await asyncio.gather(*tasks)
        my_files_to_add = [os.path.basename(f_name) for f_name in my_files_to_add]
        my_files_db_ += my_files_to_add
        db_list_ += my_files_to_add
        update_ = {
            my_files_list_comp: gr.update(value=None),
            my_files_add_to_db_btn: gr.update(visible=False),
            my_files_db_var: gr.update(value=my_files_db_),
            generate_btn: gr.update(interactive=True),
            db_reset_btn: gr.update(visible=True),
            db_list_comp: gr.update(
                visible=True,
                value=db_list_,
                choices=db_list_,
                label="Database content"),
        }
        return update_


    wiki_source_var: [str] = gr.State([])  # list of wikipage titles of interest for the input text tasks
    wiki_db_var: [str] = gr.State([])  # list of wiki document titles in the db (as seen from the UI)
    my_files_db_var: [str] = gr.State([])  # list of titles of the files uploaded in the db (as seen from the UI)
    db_collection_var: str = gr.State(-1)  # name of the collection of documents sources in the db

    source_radio\
        .change(source1_fn, inputs=[source_radio, db_collection_var], outputs=[db_col, db_collection_var])\
        .then(source2_fn, inputs=[db_collection_var], outputs=[])
    db_add_doc_btn.click(db_add_doc_fn, inputs=[], outputs=[db_add_doc_btn, add_col])
    add_close_btn.click(add_close_fn, inputs=[], outputs=[db_add_doc_btn, add_col])

    wiki_fetch_btn\
        .click(wiki_fetch1_fn, inputs=[], outputs=[wiki_list_comp])\
        .then(wiki_fetch2_fn,
              inputs=[wiki_db_var, input_text],
              outputs=[wiki_list_comp, wiki_source_var, wiki_add_to_db_btn])

    wiki_add_to_db_btn.click(wiki_add_to_db_fn,
                             inputs=[wiki_list_comp, wiki_source_var, wiki_db_var, db_list_comp, db_collection_var],
                             outputs=[db_list_comp, wiki_list_comp, wiki_db_var,
                                      generate_btn, wiki_add_to_db_btn, db_reset_btn])

    my_files_list_comp.change(my_files_list_fn, inputs=[my_files_list_comp], outputs=[my_files_add_to_db_btn])
    my_files_add_to_db_btn.click(my_files_add_to_db_fn,
                                 inputs=[my_files_list_comp, my_files_db_var, db_list_comp],
                                 outputs=[my_files_add_to_db_btn, my_files_list_comp, my_files_db_var,
                                          db_reset_btn, generate_btn, db_list_comp])
    db_reset_btn.click(db_reset_fn,
                       inputs=[wiki_source_var, db_collection_var],
                       outputs=[wiki_db_var, my_files_db_var, db_list_comp, db_reset_btn,
                                db_add_doc_btn, wiki_list_comp, wiki_add_to_db_btn])

    """
    --------------------
    B.3 Logic for generation
    --------------------
    """


    def generate_fn(input_text_, source_, db_collection_, db_list_):
        """
        generates the final text starting from the input text and the source : either "public" or private = from
        documents stored in the collection in the db
        """
        rand_dir_path = "./" + str(np.random.randint(1000))
        os.mkdir(rand_dir_path)
        fpath = rand_dir_path + "/generated_text.txt"
        f_ = open(fpath, "w")

        if source_ == "Unknown sources":
            output_text_ = control.generate_doc_from_gpt(input_text_)
        else:
            coll = db_collection_
            output_text_ = control.generate_doc_from_db(input_txt=input_text_,
                                                        collection_name=coll,
                                                        from_files=db_list_)
        f_.write(output_text_)
        f_.seek(0)

        update_ = {
            output_text: gr.update(value=output_text_),
            generated_file: gr.update(visible=True, value=f_.name),
        }
        return update_


    generate_btn.click(generate_fn,
                       inputs=[input_text, source_radio, db_collection_var, db_list_comp],
                       outputs=[output_text, generated_file])

    """
    ==================================
    Launch
    ==================================
    """

gptdoc.queue().launch()