OnurKerimoglu commited on
Commit
6190634
·
1 Parent(s): e5a546f

Introduced app.py: a rag chatbot

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from src.rag import RAG
3
+
4
+ def upload_files(files, filepaths):
5
+ verbose = False
6
+ filepaths_new = [file.name for file in files]
7
+ if verbose:
8
+ print(f'previous files: {filepaths}')
9
+ print(f'new files: {filepaths_new}')
10
+ filepaths = filepaths + filepaths_new
11
+ return filepaths, filepaths
12
+
13
+ def initialize_rag(pdfs):
14
+ print(f'Initializing RAG-Chatbot with:\npdfs:\n{pdfs}')
15
+ # Initialize RAG instance
16
+ try:
17
+ rag = RAG(
18
+ urls=[],
19
+ pdfs=pdfs,
20
+ k=2
21
+ )
22
+ message = "RAG-Chatbot initialized successfully!"
23
+ except Exception as e:
24
+ rag = None
25
+ message = f"Error initializing RAG-Chatbot:\n{e}"
26
+ return message, rag
27
+
28
+ def get_rag_response(message, history, rag):
29
+ if rag is None:
30
+ return "Error: RAG-Chatbot is not initialized yet!"
31
+ print(f"Question: {message}")
32
+ response = rag.ask_QAbot(message)
33
+ answer_str = response['answer']
34
+ sources = [f"{i+1}. {source.split('/')[-1]}" for i, source in enumerate(response['sources'])]
35
+ sources_str = ';'.join(sources)
36
+ print(sources_str)
37
+ response_str = f"""
38
+ {answer_str}
39
+
40
+ Sources:
41
+ {sources_str}
42
+ """
43
+
44
+ return response_str
45
+
46
+ with gr.Blocks() as demo:
47
+ gr.Markdown("Define References")
48
+ # PDFs
49
+ pdfpaths = gr.State([])
50
+ file_output = gr.File()
51
+ upload_button = gr.UploadButton("Upload PDF(s)", file_count="multiple")
52
+ upload_button.upload(
53
+ fn=upload_files,
54
+ inputs=[upload_button, pdfpaths],
55
+ outputs=[file_output, pdfpaths])
56
+ # State to store the RAG instance
57
+ rag_instance = gr.State(None) # Initially None
58
+ init_button = gr.Button("Initialize RAG-Chatbot")
59
+ init_status = gr.Textbox(label="Initialization Status", interactive=False)
60
+ # Event handlers
61
+ init_button.click(
62
+ initialize_rag,
63
+ inputs=[pdfpaths],
64
+ outputs=[init_status, rag_instance] # Output: status message and the RAG instance
65
+ )
66
+ gr.Markdown('## Chat with Rag-Chatbot')
67
+ # Chat Interface for RAG-Chatbot
68
+ gr.ChatInterface(
69
+ fn=get_rag_response,
70
+ additional_inputs=[rag_instance],
71
+ type="messages"
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ demo.launch()
76
+