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1 |
+
import gradio as gr
|
2 |
+
from typing import Any
|
3 |
+
from langchain.vectorstores import Chroma
|
4 |
+
from langchain.chat_models import ChatOpenAI
|
5 |
+
from langchain.document_loaders import PyPDFLoader
|
6 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
7 |
+
from langchain.chains import ConversationalRetrievalChain
|
8 |
+
|
9 |
+
import re
|
10 |
+
import uuid
|
11 |
+
import chromadb
|
12 |
+
|
13 |
+
|
14 |
+
title = 'DocTalker'
|
15 |
+
description = """ PDFs Conversing Naturally. Extract insights, ask questions, get instant context. Transforming documents into dynamic dialogues. Engage intelligently with your content."""
|
16 |
+
|
17 |
+
# enable_box = gr.Textbox.update(value = None, placeholder = 'Upload your OpenAI API key',interactive = True)
|
18 |
+
disable_box = gr.Textbox.update(value = 'OpenAI API key is Set', interactive = False)
|
19 |
+
|
20 |
+
def set_apikey(api_key: str):
|
21 |
+
app.OPENAI_API_KEY = api_key
|
22 |
+
return disable_box
|
23 |
+
|
24 |
+
# def enable_api_box():
|
25 |
+
# return enable_box
|
26 |
+
|
27 |
+
def add_text(history, text: str):
|
28 |
+
if not text:
|
29 |
+
raise gr.Error('enter text')
|
30 |
+
history = history + [(text,'')]
|
31 |
+
return history
|
32 |
+
|
33 |
+
class my_app:
|
34 |
+
def __init__(self, OPENAI_API_KEY: str = None) -> None:
|
35 |
+
self.OPENAI_API_KEY: str = OPENAI_API_KEY
|
36 |
+
self.chain = None
|
37 |
+
self.chat_history: list = []
|
38 |
+
self.N: int = 0
|
39 |
+
self.count: int = 0
|
40 |
+
self.model_type: str = ''
|
41 |
+
self.max_token: int = 0
|
42 |
+
|
43 |
+
def __call__(self, file: str) -> Any:
|
44 |
+
if self.count==0:
|
45 |
+
self.chain = self.build_chain(file)
|
46 |
+
self.count+=1
|
47 |
+
else:
|
48 |
+
self.chain = None
|
49 |
+
self.chat_history = [] # Clear chat history
|
50 |
+
self.N = 0
|
51 |
+
self.count = 0
|
52 |
+
self.model_type = ''
|
53 |
+
self.max_token = 0
|
54 |
+
self.chain = self.build_chain(file)
|
55 |
+
return self.chain
|
56 |
+
|
57 |
+
def chroma_client(self):
|
58 |
+
#create a chroma client
|
59 |
+
client = chromadb.Client()
|
60 |
+
#create a collection
|
61 |
+
collection = client.get_or_create_collection(name="my-collection")
|
62 |
+
return client
|
63 |
+
|
64 |
+
def process_file(self,file: str):
|
65 |
+
loader = PyPDFLoader(file.name)
|
66 |
+
documents = loader.load()
|
67 |
+
pattern = r"/([^/]+)$"
|
68 |
+
match = re.search(pattern, file.name)
|
69 |
+
file_name = match.group(1)
|
70 |
+
return documents, file_name
|
71 |
+
|
72 |
+
def build_chain(self, file: str):
|
73 |
+
if not self.model_type:
|
74 |
+
raise ValueError("Model type must be set before building the chain.")
|
75 |
+
documents, file_name = self.process_file(file)
|
76 |
+
#Load embeddings model
|
77 |
+
embeddings = OpenAIEmbeddings(openai_api_key=self.OPENAI_API_KEY)
|
78 |
+
pdfsearch = Chroma.from_documents(documents, embeddings, collection_name= file_name,)
|
79 |
+
# print(self.model_type)
|
80 |
+
chain = ConversationalRetrievalChain.from_llm(
|
81 |
+
ChatOpenAI(
|
82 |
+
temperature = 0.0,
|
83 |
+
openai_api_key = self.OPENAI_API_KEY,
|
84 |
+
model_name = self.model_type,
|
85 |
+
max_tokens = self.max_token
|
86 |
+
),
|
87 |
+
retriever=pdfsearch.as_retriever(search_kwargs={"k": 1}),
|
88 |
+
return_source_documents=True,)
|
89 |
+
return chain
|
90 |
+
|
91 |
+
|
92 |
+
def get_response(history, query, file):
|
93 |
+
print(app.model_type)
|
94 |
+
chain = app.chain
|
95 |
+
result = chain({"question": query, 'chat_history':app.chat_history},return_only_outputs=True)
|
96 |
+
app.chat_history += [(query, result["answer"])]
|
97 |
+
app.N = list(result['source_documents'][0])[1][1]['page']
|
98 |
+
for char in result['answer']:
|
99 |
+
history[-1][-1] += char
|
100 |
+
yield history,''
|
101 |
+
|
102 |
+
def drop_value(file, typeM: str):
|
103 |
+
app.model_type = typeM
|
104 |
+
print(typeM)
|
105 |
+
|
106 |
+
def slide_value(file, value: int):
|
107 |
+
app.max_token = value # Assuming you have a max_token attribute in your app class
|
108 |
+
print(value)
|
109 |
+
|
110 |
+
def confirm_update(file):
|
111 |
+
# Call app(file) once after updating attributes
|
112 |
+
app(file)
|
113 |
+
print('file loaded')
|
114 |
+
return [gr.update(visible=True),gr.update(visible=False),gr.update(visible=False)]
|
115 |
+
|
116 |
+
def update_textbox(selected_value):
|
117 |
+
return selected_value
|
118 |
+
input_box.value = selected_value
|
119 |
+
|
120 |
+
app = my_app()
|
121 |
+
with gr.Blocks() as demo:
|
122 |
+
gr.Markdown(f'<center><h1>{title}</h1></center>')
|
123 |
+
gr.Markdown(f'<center>{description}</center>')
|
124 |
+
with gr.Column():
|
125 |
+
with gr.Row():
|
126 |
+
with gr.Column(scale=0.8):
|
127 |
+
api_key = gr.Textbox(placeholder='Enter OpenAI API key and press enter', show_label=False, interactive=True).style(container=False)
|
128 |
+
with gr.Column(scale=0.2):
|
129 |
+
# change_api_key = gr.Button('Get OpenAI API Key', link="https://platform.openai.com/account/api-keys")
|
130 |
+
gr.Markdown(
|
131 |
+
'<button style="color: black;padding: 7px 20px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;cursor: pointer;border: 2px solid #e5e7ed;border-radius: 8px;background-color: #e9ebee;"><a style="text-decoration: none;color: black;" href="https://platform.openai.com/account/api-keys">Get OpenAI API key here</a></button>'
|
132 |
+
)
|
133 |
+
with gr.Row():
|
134 |
+
with gr.Column(min_width=400):
|
135 |
+
pdf_url = gr.Textbox(label='Enter PDF URL here')
|
136 |
+
gr.Markdown("<center><h4>OR<h4></center>")
|
137 |
+
btn = gr.File(
|
138 |
+
label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf']
|
139 |
+
)
|
140 |
+
# btn = gr.UploadButton("📁 upload a PDF", file_types=[".pdf"]).style()
|
141 |
+
drop = gr.Dropdown(label="Select Model", info="GEN AI model", choices=["gpt-4-32k", "gpt-4", "gpt-3.5-turbo", "gpt-3.5-turbo-16k"])
|
142 |
+
slide = gr.Slider(0, 2048, step=20, label="Max Token", info="Change output Token size according",interactive=True)
|
143 |
+
update_btn = gr.Button('Update App')
|
144 |
+
confirm_btn = gr.Button("Confirm Update", variant="stop", visible=False)
|
145 |
+
cancel_btn = gr.Button("Cancel", visible=False)
|
146 |
+
drop_qus = gr.Dropdown(
|
147 |
+
label="PRE-SET QUESTIONS",
|
148 |
+
info="Click a question to automatically populate the input box, and then hit Enter!",
|
149 |
+
choices=[
|
150 |
+
"Highlighted document equations or formulas?",
|
151 |
+
"What specific areas does this document cover?",
|
152 |
+
"Which theories are explored within this document?",
|
153 |
+
"Are there any notable equations or formulas highlighted in the content?",
|
154 |
+
"What is the central focus of this document or PDF?",
|
155 |
+
"Could you offer a concise overview of the main points in this material?",
|
156 |
+
"What limitations or shortcomings were identified in the study?",
|
157 |
+
"Can you summarize the main contributions or advancements outlined?",
|
158 |
+
"What conclusion or final remarks are provided in this paper?"
|
159 |
+
]
|
160 |
+
)
|
161 |
+
with gr.Column(min_width=600):
|
162 |
+
chatbot = gr.Chatbot(value=[], label='Doctalker', elem_id='chatbot').style(height=550)
|
163 |
+
input_box = gr.Textbox(
|
164 |
+
show_label=False,
|
165 |
+
container=False,
|
166 |
+
placeholder="Enter text and press enter",
|
167 |
+
)#.style(container=False)
|
168 |
+
# with gr.Row():
|
169 |
+
# with gr.Column(min_width=400):
|
170 |
+
# dataset_selection = gr.Dataset(
|
171 |
+
# components=[gr.Textbox(visible=False)],
|
172 |
+
# label="PRE-SET QUESTIONS: Click a question to automatically populate the input box, and then hit Enter!",
|
173 |
+
# samples=[
|
174 |
+
# ["Highlighted document equations or formulas?"],
|
175 |
+
# ["What specific areas does this document cover?"],
|
176 |
+
# ["Which theories are explored within this document?"],
|
177 |
+
# ["Are there any notable equations or formulas highlighted in the content?"],
|
178 |
+
# ["What is the central focus of this document or PDF?"],
|
179 |
+
# ["Could you offer a concise overview of the main points in this material?"],
|
180 |
+
# ["What limitations or shortcomings were identified in the study?"],
|
181 |
+
# ["Can you summarize the main contributions or advancements outlined?"],
|
182 |
+
# ["What conclusion or final remarks are provided in this paper?"]
|
183 |
+
# ],
|
184 |
+
# )
|
185 |
+
|
186 |
+
# with gr.Column(min_width=200):
|
187 |
+
# submit_btn = gr.Button('submit')
|
188 |
+
|
189 |
+
print(api_key)
|
190 |
+
api_key.submit(
|
191 |
+
fn=set_apikey,
|
192 |
+
inputs=[api_key],
|
193 |
+
outputs=[api_key,])
|
194 |
+
|
195 |
+
drop.change(
|
196 |
+
fn=drop_value,
|
197 |
+
inputs=[btn, drop],
|
198 |
+
outputs=[])
|
199 |
+
|
200 |
+
slide.change(
|
201 |
+
fn=slide_value,
|
202 |
+
inputs=[btn, slide],
|
203 |
+
outputs=[])
|
204 |
+
|
205 |
+
update_btn.click(lambda :[gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)], None, [update_btn, confirm_btn, cancel_btn])
|
206 |
+
cancel_btn.click(lambda :[gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)], None, [update_btn, confirm_btn, cancel_btn])
|
207 |
+
|
208 |
+
confirm_btn.click(
|
209 |
+
fn=confirm_update,
|
210 |
+
inputs=[btn],
|
211 |
+
outputs=[update_btn, confirm_btn, cancel_btn]
|
212 |
+
)
|
213 |
+
|
214 |
+
drop_qus.change(
|
215 |
+
fn=update_textbox,
|
216 |
+
inputs=[drop_qus],
|
217 |
+
outputs=[input_box]
|
218 |
+
)
|
219 |
+
|
220 |
+
input_box.submit(
|
221 |
+
fn=add_text,
|
222 |
+
inputs=[chatbot,input_box],
|
223 |
+
outputs=[chatbot, ],
|
224 |
+
queue=False).success(
|
225 |
+
fn=get_response,
|
226 |
+
inputs = [chatbot, input_box, btn],
|
227 |
+
outputs = [chatbot,input_box])
|
228 |
+
|
229 |
+
# submit_btn.click(
|
230 |
+
# fn=add_text,
|
231 |
+
# inputs=[chatbot,txt],
|
232 |
+
# outputs=[chatbot, ],
|
233 |
+
# queue=False).success(
|
234 |
+
# fn=get_response,
|
235 |
+
# inputs = [chatbot, txt, btn],
|
236 |
+
# outputs = [chatbot,txt])
|
237 |
+
|
238 |
+
|
239 |
+
demo.queue()
|
240 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio == 3.27.0
|
2 |
+
openai == 0.27.4
|
3 |
+
python-dotenv == 1.0.0
|
4 |
+
langchain == 0.0.148
|
5 |
+
chromadb == 0.4.5
|
6 |
+
tiktoken == 0.3.3
|
7 |
+
pypdf == 3.8.1
|
8 |
+
pymupdf == 1.22.2
|