th8m0z commited on
Commit
bc9f64b
1 Parent(s): cd43ca2

file names changed

Browse files
Files changed (4) hide show
  1. app.py +65 -151
  2. functions.py +154 -0
  3. requirements.txt +1 -1
  4. ui.py +0 -68
app.py CHANGED
@@ -1,154 +1,68 @@
1
- import urllib.request
2
- import fitz
3
- import re
4
- import openai
5
- import os
6
- from semantic_search import SemanticSearch
7
-
8
- recommender = SemanticSearch()
9
-
10
- def download_pdf(url, output_path):
11
- urllib.request.urlretrieve(url, output_path)
12
-
13
-
14
- def preprocess(text):
15
- text = text.replace('\n', ' ')
16
- text = re.sub('\s+', ' ', text)
17
- return text
18
-
19
-
20
- # converts pdf to text
21
- def pdf_to_text(path, start_page=1, end_page=None):
22
- doc = fitz.open(path)
23
- total_pages = doc.page_count
24
-
25
- if end_page is None:
26
- end_page = total_pages
27
-
28
- text_list = []
29
-
30
- for i in range(start_page-1, end_page):
31
- text = doc.load_page(i).get_text("text")
32
- text = preprocess(text)
33
- text_list.append(text)
34
-
35
- doc.close()
36
- return text_list
37
-
38
- # converts a text into a list of chunks
39
- def text_to_chunks(texts, word_length=150, start_page=1, file_number=1):
40
-
41
- filtered_texts = [''.join(char for char in text if ord(char) < 128) for text in texts]
42
- text_toks = [t.split(' ') for t in filtered_texts]
43
- chunks = []
44
-
45
- for idx, words in enumerate(text_toks):
46
- for i in range(0, len(words), word_length):
47
- chunk = words[i:i+word_length]
48
- if (i+word_length) > len(words) and (len(chunk) < word_length) and (
49
- len(text_toks) != (idx+1)):
50
- text_toks[idx+1] = chunk + text_toks[idx+1]
51
- continue
52
- chunk = ' '.join(chunk).strip()
53
- chunk = f'[PDF no. {file_number}] [Page no. {idx+start_page}]' + ' ' + '"' + chunk + '"'
54
- chunks.append(chunk)
55
- return chunks
56
-
57
-
58
- # merges a list of pdfs into a list of chunks and fits the recommender
59
- def load_recommender(paths, start_page=1):
60
- global recommender
61
- chunks = []
62
- for idx, path in enumerate(paths):
63
- chunks += text_to_chunks(pdf_to_text(path, start_page=start_page), start_page=start_page, file_number=idx+1)
64
- recommender.fit(chunks)
65
- return 'Corpus Loaded.'
66
-
67
-
68
- # calls the OpenAI API to generate a response for the given query
69
- def generate_text(openAI_key, prompt, model="gpt-3.5-turbo"):
70
- openai.api_key = openAI_key
71
- temperature=0.7
72
- max_tokens=256
73
- top_p=1
74
- frequency_penalty=0
75
- presence_penalty=0
76
 
77
- if model == "text-davinci-003":
78
- completions = openai.Completion.create(
79
- engine=model,
80
- prompt=prompt,
81
- max_tokens=max_tokens,
82
- n=1,
83
- stop=None,
84
- temperature=temperature,
85
- )
86
- message = completions.choices[0].text
87
- else:
88
- message = openai.ChatCompletion.create(
89
- model=model,
90
- messages=[
91
- {"role": "system", "content": "You are a helpful assistant."},
92
- {"role": "assistant", "content": "Here is some initial assistant message."},
93
- {"role": "user", "content": prompt}
94
- ],
95
- temperature=.3,
96
- max_tokens=max_tokens,
97
- top_p=top_p,
98
- frequency_penalty=frequency_penalty,
99
- presence_penalty=presence_penalty,
100
- ).choices[0].message['content']
101
- return message
102
 
103
 
104
- # constructs the prompt for the given query
105
- def construct_prompt(question):
106
- topn_chunks = recommender(question)
107
- prompt = 'search results:\n\n'
108
- for c in topn_chunks:
109
- prompt += c + '\n\n'
110
-
111
- prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
112
- "Cite each reference using [PDF Number][Page Number] notation. "\
113
- "Only answer what is asked. The answer should be short and concise. \n\nQuery: "
114
-
115
- prompt += f"{question}\nAnswer:"
116
- return prompt
117
-
118
- # main function that is called when the user clicks the submit button, generates an answer for the query
119
- def question_answer(chat_history, url, files, question, openAI_key, model):
120
- try:
121
- if files == None:
122
- files = []
123
- if openAI_key.strip()=='':
124
- return '[ERROR]: Please enter your Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
125
- if url.strip() == '' and files == []:
126
- return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
127
- if url.strip() != '' and files is not []:
128
- return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
129
- if model is None or model =='':
130
- return '[ERROR]: You have not selected any model. Please choose an LLM model.'
131
- if url.strip() != '':
132
- glob_url = url
133
- download_pdf(glob_url, 'corpus.pdf')
134
- load_recommender('corpus.pdf')
135
- else:
136
- print(files)
137
- filenames = []
138
- for file in files:
139
- old_file_name = file.name
140
- file_name = file.name
141
- file_name = file_name[:-12] + file_name[-4:]
142
- os.rename(old_file_name, file_name)
143
- filenames.append(file_name)
144
- load_recommender(filenames)
145
-
146
-
147
- if question.strip() == '':
148
- return '[ERROR]: Question field is empty'
149
- prompt = construct_prompt(question)
150
- answer = generate_text(openAI_key, prompt, model)
151
- chat_history.append([question, answer])
152
- return chat_history
153
- except openai.error.InvalidRequestError as e:
154
- return f'[ERROR]: Either you do not have access to GPT4 or you have exhausted your quota!'
 
1
+ import gradio as gr
2
+ import app as app
3
+
4
+ # pre-defined questions
5
+ questions = [
6
+ "What did the study investigate?",
7
+ "Can you provide a summary of this paper?",
8
+ "what are the methodologies used in this study?",
9
+ "what are the data intervals used in this study? Give me the start dates and end dates?",
10
+ "what are the main limitations of this study?",
11
+ "what are the main shortcomings of this study?",
12
+ "what are the main findings of the study?",
13
+ "what are the main results of the study?",
14
+ "what are the main contributions of this study?",
15
+ "what is the conclusion of this paper?",
16
+ "what are the input features used in this study?",
17
+ "what is the dependent variable in this study?",
18
+ ]
19
+
20
+ title = 'PDF GPT Turbo'
21
+ description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
22
+
23
+ with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
24
+
25
+ gr.Markdown(f'<center><h3>{title}</h3></center>')
26
+ gr.Markdown(description)
27
+
28
+ with gr.Row():
29
+
30
+ with gr.Group():
31
+ gr.Markdown(f'<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>')
32
+ with gr.Accordion("API Key"):
33
+ openAI_key = gr.Textbox(label='Enter your OpenAI API key here', password=True)
34
+ url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
35
+ gr.Markdown("<center><h4>OR<h4></center>")
36
+ files = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'], file_count="multiple")
37
+ question = gr.Textbox(label='Enter your question here')
38
+ gr.Examples(
39
+ [[q] for q in questions],
40
+ inputs=[question],
41
+ label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
42
+ )
43
+ model = gr.Radio([
44
+ 'gpt-3.5-turbo',
45
+ 'gpt-3.5-turbo-16k',
46
+ 'gpt-3.5-turbo-0613',
47
+ 'gpt-3.5-turbo-16k-0613',
48
+ 'text-davinci-003',
49
+ 'gpt-4',
50
+ 'gpt-4-32k'
51
+ ], label='Select Model', default='gpt-3.5-turbo')
52
+ btn = gr.Button(value='Submit')
53
+
54
+ btn.style(full_width=True)
55
+
56
+ with gr.Group():
57
+ chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
 
61
+ # Bind the click event of the button to the question_answer function
62
+ btn.click(
63
+ app.question_answer,
64
+ inputs=[chatbot, url, files, question, openAI_key, model],
65
+ outputs=[chatbot],
66
+ )
67
+
68
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
functions.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.request
2
+ import fitz
3
+ import re
4
+ import openai
5
+ import os
6
+ from semantic_search import SemanticSearch
7
+
8
+ recommender = SemanticSearch()
9
+
10
+ def download_pdf(url, output_path):
11
+ urllib.request.urlretrieve(url, output_path)
12
+
13
+
14
+ def preprocess(text):
15
+ text = text.replace('\n', ' ')
16
+ text = re.sub('\s+', ' ', text)
17
+ return text
18
+
19
+
20
+ # converts pdf to text
21
+ def pdf_to_text(path, start_page=1, end_page=None):
22
+ doc = fitz.open(path)
23
+ total_pages = doc.page_count
24
+
25
+ if end_page is None:
26
+ end_page = total_pages
27
+
28
+ text_list = []
29
+
30
+ for i in range(start_page-1, end_page):
31
+ text = doc.load_page(i).get_text("text")
32
+ text = preprocess(text)
33
+ text_list.append(text)
34
+
35
+ doc.close()
36
+ return text_list
37
+
38
+ # converts a text into a list of chunks
39
+ def text_to_chunks(texts, word_length=150, start_page=1, file_number=1):
40
+
41
+ filtered_texts = [''.join(char for char in text if ord(char) < 128) for text in texts]
42
+ text_toks = [t.split(' ') for t in filtered_texts]
43
+ chunks = []
44
+
45
+ for idx, words in enumerate(text_toks):
46
+ for i in range(0, len(words), word_length):
47
+ chunk = words[i:i+word_length]
48
+ if (i+word_length) > len(words) and (len(chunk) < word_length) and (
49
+ len(text_toks) != (idx+1)):
50
+ text_toks[idx+1] = chunk + text_toks[idx+1]
51
+ continue
52
+ chunk = ' '.join(chunk).strip()
53
+ chunk = f'[PDF no. {file_number}] [Page no. {idx+start_page}]' + ' ' + '"' + chunk + '"'
54
+ chunks.append(chunk)
55
+ return chunks
56
+
57
+
58
+ # merges a list of pdfs into a list of chunks and fits the recommender
59
+ def load_recommender(paths, start_page=1):
60
+ global recommender
61
+ chunks = []
62
+ for idx, path in enumerate(paths):
63
+ chunks += text_to_chunks(pdf_to_text(path, start_page=start_page), start_page=start_page, file_number=idx+1)
64
+ recommender.fit(chunks)
65
+ return 'Corpus Loaded.'
66
+
67
+
68
+ # calls the OpenAI API to generate a response for the given query
69
+ def generate_text(openAI_key, prompt, model="gpt-3.5-turbo"):
70
+ openai.api_key = openAI_key
71
+ temperature=0.7
72
+ max_tokens=256
73
+ top_p=1
74
+ frequency_penalty=0
75
+ presence_penalty=0
76
+
77
+ if model == "text-davinci-003":
78
+ completions = openai.Completion.create(
79
+ engine=model,
80
+ prompt=prompt,
81
+ max_tokens=max_tokens,
82
+ n=1,
83
+ stop=None,
84
+ temperature=temperature,
85
+ )
86
+ message = completions.choices[0].text
87
+ else:
88
+ message = openai.ChatCompletion.create(
89
+ model=model,
90
+ messages=[
91
+ {"role": "system", "content": "You are a helpful assistant."},
92
+ {"role": "assistant", "content": "Here is some initial assistant message."},
93
+ {"role": "user", "content": prompt}
94
+ ],
95
+ temperature=.3,
96
+ max_tokens=max_tokens,
97
+ top_p=top_p,
98
+ frequency_penalty=frequency_penalty,
99
+ presence_penalty=presence_penalty,
100
+ ).choices[0].message['content']
101
+ return message
102
+
103
+
104
+ # constructs the prompt for the given query
105
+ def construct_prompt(question):
106
+ topn_chunks = recommender(question)
107
+ prompt = 'search results:\n\n'
108
+ for c in topn_chunks:
109
+ prompt += c + '\n\n'
110
+
111
+ prompt += "Instructions: Compose a comprehensive reply to the query using the search results given. "\
112
+ "Cite each reference using [PDF Number][Page Number] notation. "\
113
+ "Only answer what is asked. The answer should be short and concise. \n\nQuery: "
114
+
115
+ prompt += f"{question}\nAnswer:"
116
+ return prompt
117
+
118
+ # main function that is called when the user clicks the submit button, generates an answer for the query
119
+ def question_answer(chat_history, url, files, question, openAI_key, model):
120
+ try:
121
+ if files == None:
122
+ files = []
123
+ if openAI_key.strip()=='':
124
+ return '[ERROR]: Please enter your Open AI Key. Get your key here : https://platform.openai.com/account/api-keys'
125
+ if url.strip() == '' and files == []:
126
+ return '[ERROR]: Both URL and PDF is empty. Provide at least one.'
127
+ if url.strip() != '' and files is not []:
128
+ return '[ERROR]: Both URL and PDF is provided. Please provide only one (either URL or PDF).'
129
+ if model is None or model =='':
130
+ return '[ERROR]: You have not selected any model. Please choose an LLM model.'
131
+ if url.strip() != '':
132
+ glob_url = url
133
+ download_pdf(glob_url, 'corpus.pdf')
134
+ load_recommender('corpus.pdf')
135
+ else:
136
+ print(files)
137
+ filenames = []
138
+ for file in files:
139
+ old_file_name = file.name
140
+ file_name = file.name
141
+ file_name = file_name[:-12] + file_name[-4:]
142
+ os.rename(old_file_name, file_name)
143
+ filenames.append(file_name)
144
+ load_recommender(filenames)
145
+
146
+
147
+ if question.strip() == '':
148
+ return '[ERROR]: Question field is empty'
149
+ prompt = construct_prompt(question)
150
+ answer = generate_text(openAI_key, prompt, model)
151
+ chat_history.append([question, answer])
152
+ return chat_history
153
+ except openai.error.InvalidRequestError as e:
154
+ return f'[ERROR]: Either you do not have access to GPT4 or you have exhausted your quota!'
requirements.txt CHANGED
@@ -2,6 +2,6 @@ gradio
2
  PyMuPDF
3
  numpy
4
  scikit-learn
5
- tensorflow==2.13.0
6
  tensorflow-hub
7
  openai
 
2
  PyMuPDF
3
  numpy
4
  scikit-learn
5
+ tensorflow
6
  tensorflow-hub
7
  openai
ui.py DELETED
@@ -1,68 +0,0 @@
1
- import gradio as gr
2
- import app as app
3
-
4
- # pre-defined questions
5
- questions = [
6
- "What did the study investigate?",
7
- "Can you provide a summary of this paper?",
8
- "what are the methodologies used in this study?",
9
- "what are the data intervals used in this study? Give me the start dates and end dates?",
10
- "what are the main limitations of this study?",
11
- "what are the main shortcomings of this study?",
12
- "what are the main findings of the study?",
13
- "what are the main results of the study?",
14
- "what are the main contributions of this study?",
15
- "what is the conclusion of this paper?",
16
- "what are the input features used in this study?",
17
- "what is the dependent variable in this study?",
18
- ]
19
-
20
- title = 'PDF GPT Turbo'
21
- description = """ PDF GPT Turbo allows you to chat with your PDF files. It uses Google's Universal Sentence Encoder with Deep averaging network (DAN) to give hallucination free response by improving the embedding quality of OpenAI. It cites the page number in square brackets([Page No.]) and shows where the information is located, adding credibility to the responses."""
22
-
23
- with gr.Blocks(css="""#chatbot { font-size: 14px; min-height: 1200; }""") as demo:
24
-
25
- gr.Markdown(f'<center><h3>{title}</h3></center>')
26
- gr.Markdown(description)
27
-
28
- with gr.Row():
29
-
30
- with gr.Group():
31
- gr.Markdown(f'<p style="text-align:center">Get your Open AI API key <a href="https://platform.openai.com/account/api-keys">here</a></p>')
32
- with gr.Accordion("API Key"):
33
- openAI_key = gr.Textbox(label='Enter your OpenAI API key here', password=True)
34
- url = gr.Textbox(label='Enter PDF URL here (Example: https://arxiv.org/pdf/1706.03762.pdf )')
35
- gr.Markdown("<center><h4>OR<h4></center>")
36
- files = gr.File(label='Upload your PDF/ Research Paper / Book here', file_types=['.pdf'], file_count="multiple")
37
- question = gr.Textbox(label='Enter your question here')
38
- gr.Examples(
39
- [[q] for q in questions],
40
- inputs=[question],
41
- label="PRE-DEFINED QUESTIONS: Click on a question to auto-fill the input box, then press Enter!",
42
- )
43
- model = gr.Radio([
44
- 'gpt-3.5-turbo',
45
- 'gpt-3.5-turbo-16k',
46
- 'gpt-3.5-turbo-0613',
47
- 'gpt-3.5-turbo-16k-0613',
48
- 'text-davinci-003',
49
- 'gpt-4',
50
- 'gpt-4-32k'
51
- ], label='Select Model', default='gpt-3.5-turbo')
52
- btn = gr.Button(value='Submit')
53
-
54
- btn.style(full_width=True)
55
-
56
- with gr.Group():
57
- chatbot = gr.Chatbot(placeholder="Chat History", label="Chat History", lines=50, elem_id="chatbot")
58
-
59
-
60
-
61
- # Bind the click event of the button to the question_answer function
62
- btn.click(
63
- app.question_answer,
64
- inputs=[chatbot, url, files, question, openAI_key, model],
65
- outputs=[chatbot],
66
- )
67
-
68
- demo.launch()