-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend_api.py
366 lines (282 loc) · 11.2 KB
/
backend_api.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import openai
import PyPDF2
import re
import json
import requests
# import cohere
import json
from unpywall import Unpywall
from unpywall.utils import UnpywallCredentials
from dotenv import load_dotenv
import os
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
scopusKey = os.getenv("SCOPUS_API_KEY")
primoAPI = os.getenv("PRIMO_API_KEY")
UnpywallCredentials("[email protected]")
# Loop through all the retrived DOIs from Scopus/Semantic Scholar to check if there are OpenAccess Articles
def CheckOpenAccess(titleDOI, username):
count=0
for book in titleDOI:
try:
count+=1
print("file ",count,": "+book[1])
response = requests.get(Unpywall.get_pdf_link(doi=book[1]))
filename = book[0] + ".pdf"
with open(username + "/" + filename, "wb") as f:
f.write(response.content)
except:
print("Sorry, no open access articles found")
# def CheckOpenAccess(titleDOI, username):
# count=0
# for book in titleDOI:
# try:
# count+=1
# print("file ",count,": "+book[1])
# response = requests.get(Unpywall.get_pdf_link(doi=book[1]))
# filename = book[0] + ".pdf"
# test = urllib.urlopen(Unpywall.get_pdf_link(doi=book[1]))
# meta = test.info()
# if (meta.getheader("Content-Length")):
# with open(username + "/" + filename, "wb") as f:
# f.write(response.content)
# except:
# print("Sorry, no open access articles found")
def summarisation(file_directory):
def get_page_text(page):
try:
text = page.extract_text()
except:
text = ""
text = str(text)
text = text.strip()
text = re.sub(r"\W+", " ", text)
return text
def summarize_text(text):
messages = [
{
"role": "system",
"content": "Please provide a 1 sentence summary of the following:",
},
{"role": "user", "content": text},
]
response = openai.ChatCompletion.create(
model="gpt-4-0613", messages=messages
)
return response["choices"][0]["message"]["content"]
def summarize_text2_topic(text):
messages = [
{
"role": "system",
"content": "Provide a keywords for the paragraph. Return in JSON format.",
},
{"role": "user", "content": text},
]
response = openai.ChatCompletion.create(
model="gpt-4-0613", messages=messages
)
return response["choices"][0]["message"]["content"]
def summarise_cohere(text):
response = co.summarize(
text=text,
length="auto",
format="auto",
model="summarize-xlarge",
additional_command="",
temperature=0.8,
)
return response.summary
try:
pdf_file = open(file_directory, "rb")
pdf_reader = PyPDF2.PdfReader(pdf_file)
except:
return "",""
pages = len(pdf_reader.pages)
print(f"Total Pages: {pages}")
page_summaries = []
page_summary_cohere = []
for page_num in range(pages):
print(f"Summarizing page {page_num+1}...")
page = pdf_reader.pages[page_num]
text = get_page_text(page)
page_summary = summarize_text(text)
# page_ch_summary = summarise_cohere(text)
page_summaries.append(page_summary)
# page_summary_cohere.append(page_summary_cohere)
print(page_summary)
print()
print(page_summary_cohere)
all_summaries = ". ".join(page_summaries)
final_summary = summarize_text(all_summaries)
topics = summarize_text2_topic(final_summary)
# cohere_summary = summarise_cohere(final_summary)
print()
print("OpenAI's Final Summary:")
print(final_summary)
print("Topics Involved:")
print(topics)
# print("Cohere's Final Summary:")
# print(cohere_summary)
pdf_file.close()
return final_summary, json.loads(topics)
# Function for chatting with the GPT-4 based model.
def context(message, chat_context):
if not chat_context:
chat_context = {
"messages": [
{
"role": "system",
"content": "You are a ChatBot that intakes a user's broad academic or professional interest, refines it into a focused area of study or project topic, and then provides personalized resources and a learning pathway tailored to their unique goals. For instance, if a user mentions they're a Biology student but wishes to delve into data analytics, the model will offer resources on bioinformatics and a suggested learning journey",
},
{"role": "user", "content": str(message)},
]
}
else:
chat_context["messages"].append({"role": "user", "content": str(message)})
# write code to do some basic logging for debugging
print("\n")
print(chat_context)
print("\n")
response = openai.ChatCompletion.create(
model="gpt-4-0613", messages=chat_context["messages"]
)
response_message = response["choices"][0]["message"]["content"]
if not response_message:
response_message = "Our brains are on fire now. Please try again later."
# Append response to context
chat_context["messages"].append(
{"role": "assistant", "content": str(response_message)}
)
return response_message, chat_context
# def recommended_readings(topic: str):
# url = "https://api.semanticscholar.org/graph/v1/paper/search?"
# # params = {'query':topic, 'fields':"title,year,authors,externalIds", "limit": 10}
# params = {'query':topic, 'fields':"externalIds", "limit": 10}
# response = requests.get(url, params)
# recs = []
# res_dict = response.json()
# data_dict = res_dict["data"] # This is array of dicts with all info of results
# # print(data_dict)
# for item in data_dict:
# for key in item :
# #print(key)
# if (key == "externalIds"):
# if (item[key].get("DOI")):
# # print(item[key])
# doi = item[key]["DOI"]
# recs.append(doi)
# return recs
def SemanticScholar(topic : str):
# offset: skip first 10 result, limit: limit the number of records output, fields
# query':context.user_data["query"] --> the actual query from the next message
url ="http://api.semanticscholar.org/graph/v1/paper/search"
params = {'query': topic, 'fields' : "title,externalIds,isOpenAccess"}
recs = []
response = requests.get(url, params)
res_dict = response.json()
data_dict = res_dict["data"] # This is array of dicts with all info of results
# print(res_dict["total"])
#print(data_dict)
# Check if there's any results
if (res_dict["total"]>0):
# for item in data_dict:
# for key in item :
# # print(key)
# founddoi
# if (key == "externalIds"):
# if (item[key].get("DOI")):
# doi = item[key]["DOI"]
# title = item["title"]
# recs.append([title,doi])
# return recs
for item in data_dict:
# print(item)
if ("DOI" in item["externalIds"] and item["isOpenAccess"] == True):
title = item["title"]
doi = item["externalIds"]["DOI"]
recs.append([title, doi])
return recs
else:
text="Sorry, we were unable to find any articles relating to " + topic + "."
return text
def scopus(topic: str):
url = "https://api.elsevier.com/content/search/scopus?"
topic += ",OPENACCESS"
params = {"query": topic, "apikey": scopusKey}
response = requests.get(url, params)
recs = []
res_dict = response.json()
# Returns a list of all results
res = res_dict["search-results"]["entry"]
# print(res)
# print(res_dict["search-results"]["opensearch:totalResults"])
if int(res_dict["search-results"]["opensearch:totalResults"]) > 0:
for book in res:
titleDOI = []
if len(recs) > 9:
break
if book.get("prism:doi") and len(recs) < 11:
titleDOI.append(book["dc:title"])
titleDOI.append(book["prism:doi"])
recs.append(titleDOI)
else:
text = "Sorry, we were unable to find any articles relating to " + topic + "."
return text
return recs
def OpenAlexAbstract(doi: str):
url = "https://api.openalex.org/works/"
url += doi
response = requests.get(url)
res_dict = response.json()
# Returns an inverted index/ dict with key of a word that appears with values index of where it appears
abi = res_dict["abstract_inverted_index"]
# Using this to store the max value for each key which in this case is the word
len_index = []
# Add the largest number from each key value into len_index first
for indices in abi.values():
len_index.append(max(indices))
# Find the max value among all the max values in each list
max_index = max(len_index)
# Create a list to store the words in their respective positions
sentence = [""] * (max_index + 1)
# Send each word back into its original position in the sentence
for word, indices in abi.items():
for index in indices:
sentence[index] = word
# Convert the list to a string
reconstructed_sentence = " ".join(sentence)
return reconstructed_sentence
def OpenAlexRelated(topic: str):
# Used for looking for actual concepts reltaed to the search'
url = "https://api.openalex.org/concepts?"
params = {"search": topic}
response = requests.get(url, params)
related = []
res_dict = response.json()
res = res_dict["results"]
for concept in res:
if len(related) < 3:
related.append(concept["display_name"])
return related
def CheckLibrary(titleDOI: list):
# url = "https://api-ap.hosted.exlibrisgroup.com/primo/v1/search?"
found = []
notFound = []
for book in titleDOI:
searchTerm = book[1]
# params = {'vid': "65SMU_INST%3ASMU_NUI", 'tab': "Everything", 'scope': "Everything", 'q': searchTerm, "offset": 0, 'limit':10, 'pcAvailability': 'true', 'INST':"65SMU_INST"}
# params = {'vid': "65SMU_INST%3ASMU_NUI", 'tab': "Everything", 'scope': "Everything", 'q': searchTerm, 'offset': 0, 'limit':10, 'INST':"65SMU_INST", 'apikey': primoAPI}
url = (
"https://api-ap.hosted.exlibrisgroup.com/primo/v1/search?vid=65SMU_INST%3ASMU_NUI&tab=Everything&scope=Everything&q=any,contains,"
+ searchTerm
)
url2 = "&lang=eng&offset=0&limit=10&sort=rank&pcAvailability=true&getMore=0&conVoc=true&inst=65SMU_INST&skipDelivery=true&disableSplitFacets=true&apikey=<apikeyhere>"
response = requests.get(url + url2)
res_dict = response.json()
res = res_dict["info"]
if res["total"] > 0:
found.append([book[0], book[1]])
else:
print
notFound.append([book[0], book[1]])
return (found, notFound)