File size: 2,280 Bytes
ef3d4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
from tempfile import NamedTemporaryFile

import gradio as gr
from openai import OpenAI

from mylib import (
    Logger,
    FileManager,
    ChatController,
    MessageHandler,
    NumericCitations,
)

#
#
#
class ErrorLogger:
    def __init__(self, path):
        self.path = path
        if not self.path.exists():
            self.path.mkdir(parents=True, exist_ok=True)

    def dump(self, prompt, error):
        msg = {
            'prompt': prompt,
        }
        msg.update(error.to_dict())
        output = json.dumps(msg, indent=2)

        with NamedTemporaryFile(mode='w',
                                prefix='',
                                dir=self.path,
                                delete=False) as fp:
            print(output, file=fp)
            return fp.name

#
#
#
class FileChat:
    def __init__(self, client, config):
        self.database = FileManager(client, config['chat']['prefix'])
        self.messenger = MessageHandler(client, NumericCitations)
        self.chat = ChatController(client, config['openai'], config['chat'])

    def upload(self, *args):
        (data, ) = args
        return self.database(data)

    def prompt(self, *args):
        (message, *_) = args
        if not self.database:
            raise gr.Error('Please upload your documents to begin')

        return self.messenger(self.chat(message, self.database))

#
#
#
with open(os.getenv('FILE_CHAT_CONFIG')) as fp:
    config = json.load(fp)

with gr.Blocks() as demo:
    client = OpenAI(api_key=config['openai']['api_key'])
    mychat = FileChat(client, config)

    with gr.Row():
        upload = gr.UploadButton(file_count='multiple')
        text = gr.Textbox(label='Files uploaded', interactive=False)
        upload.upload(mychat.upload, upload, text)

    gr.ChatInterface(
        fn=mychat.prompt,
        additional_inputs=[
            upload,
            text,
        ],
        retry_btn=None,
        undo_btn=None,
        clear_btn=None,
        # additional_inputs_accordion=gr.Accordion(
        #     label='Upload documents',
        #     open=True,
        # ),
    )

if __name__ == '__main__':
    # demo.queue().launch(server_name='0.0.0.0', **config['gradio'])
    demo.queue().launch(server_name='0.0.0.0')