hamzaf commited on
Commit
ab4c70d
β€’
1 Parent(s): 566ff07

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #import csv
2
+ import gradio as gr
3
+ from langchain.embeddings.openai import OpenAIEmbeddings
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.vectorstores import Chroma
6
+
7
+ from langchain.chains import ConversationalRetrievalChain
8
+ from langchain.chat_models import ChatOpenAI
9
+
10
+ from langchain.document_loaders import PyPDFLoader
11
+ import os
12
+
13
+ import fitz
14
+ from PIL import Image
15
+
16
+ # Global variables
17
+ COUNT, N = 0, 0
18
+ chat_history = []
19
+ chain = ''
20
+ enable_box = gr.Textbox.update(value=None,
21
+ placeholder='Upload your OpenAI API key', interactive=True)
22
+ disable_box = gr.Textbox.update(value='OpenAI API key is Set', interactive=False)
23
+
24
+ # Function to set the OpenAI API key
25
+ def set_apikey(api_key):
26
+ os.environ['OPENAI_API_KEY'] = api_key
27
+ return disable_box
28
+
29
+ # Function to enable the API key input box
30
+ def enable_api_box():
31
+ return enable_box
32
+
33
+ # Function to add text to the chat history
34
+ def add_text(history, text):
35
+ if not text:
36
+ raise gr.Error('Enter text')
37
+ history = history + [(text, '')]
38
+ return history
39
+
40
+ # Function to process the PDF file and create a conversation chain
41
+ def process_file(file):
42
+ if 'OPENAI_API_KEY' not in os.environ:
43
+ raise gr.Error('Upload your OpenAI API key')
44
+
45
+ loader = PyPDFLoader(file.name)
46
+ documents = loader.load()
47
+
48
+ embeddings = OpenAIEmbeddings()
49
+
50
+ pdfsearch = Chroma.from_documents(documents, embeddings)
51
+
52
+ chain = ConversationalRetrievalChain.from_llm(ChatOpenAI(temperature=0.3),
53
+ retriever=pdfsearch.as_retriever(search_kwargs={"k": 1}),
54
+ return_source_documents=True)
55
+ return chain
56
+
57
+ # Function to generate a response based on the chat history and query
58
+ def generate_response(history, query, btn):
59
+ global COUNT, N, chat_history, chain
60
+
61
+ if not btn:
62
+ raise gr.Error(message='Upload a PDF')
63
+ if COUNT == 0:
64
+ chain = process_file(btn)
65
+ COUNT += 1
66
+
67
+ result = chain({"question": query, 'chat_history': chat_history}, return_only_outputs=True)
68
+ chat_history += [(query, result["answer"])]
69
+ N = list(result['source_documents'][0])[1][1]['page']
70
+
71
+ for char in result['answer']:
72
+ history[-1][-1] += char
73
+ yield history, ''
74
+
75
+ # Function to render a specific page of a PDF file as an image
76
+ def render_file(file):
77
+ global N
78
+ doc = fitz.open(file.name)
79
+ page = doc[N]
80
+ # Render the page as a PNG image with a resolution of 300 DPI
81
+ pix = page.get_pixmap(matrix=fitz.Matrix(300/72, 300/72))
82
+ image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples)
83
+ return image
84
+
85
+ # Gradio application setup
86
+ with gr.Blocks() as demo:
87
+ # Create a Gradio block
88
+
89
+ with gr.Column():
90
+ with gr.Row():
91
+ with gr.Column(scale=0.8):
92
+ api_key = gr.Textbox(
93
+ placeholder='Enter OpenAI API key',
94
+ show_label=False,
95
+ interactive=True
96
+ ).style(container=False)
97
+ with gr.Column(scale=0.2):
98
+ change_api_key = gr.Button('Change Key')
99
+
100
+ with gr.Row():
101
+ chatbot = gr.Chatbot(value=[], elem_id='chatbot').style(height=650)
102
+ show_img = gr.Image(label='Upload PDF', tool='select').style(height=680)
103
+
104
+ with gr.Row():
105
+ with gr.Column(scale=0.70):
106
+ txt = gr.Textbox(
107
+ show_label=False,
108
+ placeholder="Enter text and press enter"
109
+ ).style(container=False)
110
+
111
+ with gr.Column(scale=0.15):
112
+ submit_btn = gr.Button('Submit')
113
+
114
+ with gr.Column(scale=0.15):
115
+ btn = gr.UploadButton("πŸ“ Upload a PDF", file_types=[".pdf"]).style()
116
+
117
+ # Set up event handlers
118
+
119
+ # Event handler for submitting the OpenAI API key
120
+ api_key.submit(fn=set_apikey, inputs=[api_key], outputs=[api_key])
121
+
122
+ # Event handler for changing the API key
123
+ change_api_key.click(fn=enable_api_box, outputs=[api_key])
124
+
125
+ # Event handler for uploading a PDF
126
+ btn.upload(fn=render_first, inputs=[btn], outputs=[show_img])
127
+
128
+ # Event handler for submitting text and generating response
129
+ submit_btn.click(
130
+ fn=add_text,
131
+ inputs=[chatbot, txt],
132
+ outputs=[chatbot],
133
+ queue=False
134
+ ).success(
135
+ fn=generate_response,
136
+ inputs=[chatbot, txt, btn],
137
+ outputs=[chatbot, txt]
138
+ ).success(
139
+ fn=render_file,
140
+ inputs=[btn],
141
+ outputs=[show_img]
142
+ )
143
+ demo.queue()
144
+ if __name__ == "__main__":
145
+ demo.launch()