Update app.py
Browse files
app.py
CHANGED
@@ -2,24 +2,19 @@ import nltk
|
|
2 |
import re
|
3 |
import nltkmodule
|
4 |
|
5 |
-
from newspaper import Article
|
6 |
-
from newspaper import fulltext
|
7 |
import requests
|
8 |
import itertools
|
9 |
import os
|
10 |
|
11 |
-
|
12 |
-
from nltk.tokenize import word_tokenize
|
13 |
from sentence_transformers import SentenceTransformer
|
14 |
import pandas as pd
|
15 |
import numpy as np
|
16 |
from pandas import ExcelWriter
|
17 |
from torch.utils.data import DataLoader
|
18 |
import math
|
19 |
-
from sentence_transformers import models
|
20 |
-
from sentence_transformers import SentencesDataset, LoggingHandler, SentenceTransformer
|
21 |
-
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
|
22 |
-
from sentence_transformers.readers import *
|
23 |
from nltk.corpus import stopwords
|
24 |
stop_words = stopwords.words('english')
|
25 |
import matplotlib.pyplot as plt
|
@@ -28,7 +23,6 @@ from sklearn.decomposition import PCA
|
|
28 |
from sklearn.metrics.pairwise import cosine_similarity
|
29 |
import scipy.spatial
|
30 |
import networkx as nx
|
31 |
-
from nltk.tokenize import sent_tokenize
|
32 |
import scispacy
|
33 |
import spacy
|
34 |
import en_core_sci_lg
|
@@ -36,13 +30,13 @@ import string
|
|
36 |
from nltk.stem.wordnet import WordNetLemmatizer
|
37 |
import gradio as gr
|
38 |
import inflect
|
39 |
-
from sklearn.
|
40 |
-
from sklearn.cluster import AgglomerativeClustering
|
41 |
-
from sklearn.metrics import silhouette_samples, silhouette_score, davies_bouldin_score
|
42 |
-
import json
|
43 |
from xml.etree import ElementTree as ET
|
44 |
-
p = inflect.engine()
|
45 |
|
|
|
|
|
|
|
|
|
46 |
nlp = en_core_sci_lg.load()
|
47 |
sp = en_core_sci_lg.load()
|
48 |
all_stopwords = sp.Defaults.stop_words
|
@@ -53,307 +47,297 @@ def remove_stopwords(sen):
|
|
53 |
sen_new = " ".join([i for i in sen if i not in stop_words])
|
54 |
return sen_new
|
55 |
|
|
|
|
|
|
|
|
|
|
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
|
|
|
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
|
|
66 |
|
67 |
-
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
comb=[]
|
73 |
-
title_list=[]
|
74 |
-
titles_list=[]
|
75 |
-
abstracts_list=[]
|
76 |
-
silhouette_score_list=[]
|
77 |
-
final_textrank_list=[]
|
78 |
-
document=[]
|
79 |
-
text_doc=[]
|
80 |
-
final_list=[]
|
81 |
-
score_list=[]
|
82 |
-
sum_list=[]
|
83 |
-
############################################## Here we first extract the sentences using SBERT and Textrank ###########################
|
84 |
-
model_1 = SentenceTransformer(model_1)
|
85 |
-
model_2 = SentenceTransformer(model_2)
|
86 |
-
url = article_link
|
87 |
-
html = requests.get(url).text
|
88 |
-
article = fulltext(html)
|
89 |
-
corpus=sent_tokenize(article)
|
90 |
-
indicator_list=['concluded','concludes','in a study', 'concluding','conclude','in sum','in a recent study','therefore','thus','so','hence',
|
91 |
-
'as a result','accordingly','consequently','in short','proves that','shows that','suggests that','demonstrates that','found that','observed that',
|
92 |
-
'indicated that','suggested that','demonstrated that']
|
93 |
-
count_dict={}
|
94 |
-
for l in corpus:
|
95 |
-
c=0
|
96 |
-
for l2 in indicator_list:
|
97 |
-
if l.find(l2)!=-1:#then it is a substring
|
98 |
-
c=1
|
99 |
-
break
|
100 |
-
if c:#
|
101 |
-
count_dict[l]=1
|
102 |
-
else:
|
103 |
-
count_dict[l]=0
|
104 |
-
for sent, score in count_dict.items():
|
105 |
-
score_list.append(score)
|
106 |
-
clean_sentences_new = pd.Series(corpus).str.replace("[^a-zA-Z]", " ", regex = True).tolist()
|
107 |
-
corpus_embeddings = model_1.encode(clean_sentences_new)
|
108 |
-
sim_mat = np.zeros([len(clean_sentences_new), len(clean_sentences_new)])
|
109 |
-
for i in range(len(clean_sentences_new)):
|
110 |
-
len_embeddings=(len(corpus_embeddings[i]))
|
111 |
-
for j in range(len(clean_sentences_new)):
|
112 |
-
if i != j:
|
113 |
-
if(len_embeddings == 1024):
|
114 |
-
sim_mat[i][j] = cosine_similarity(corpus_embeddings[i].reshape(1,1024), corpus_embeddings[j].reshape(1,1024))[0,0]
|
115 |
-
elif(len_embeddings == 768):
|
116 |
-
sim_mat[i][j] = cosine_similarity(corpus_embeddings[i].reshape(1,768), corpus_embeddings[j].reshape(1,768))[0,0]
|
117 |
-
nx_graph = nx.from_numpy_array(sim_mat)
|
118 |
-
scores = nx.pagerank(nx_graph, max_iter = 1500)
|
119 |
-
sentences=((scores[i],s) for i,s in enumerate(corpus))
|
120 |
-
for elem in sentences:
|
121 |
-
element.append(elem[0])
|
122 |
-
for sc, lst in zip(score_list, element): ########## taking the scores from both the lists
|
123 |
-
sum1=sc+lst
|
124 |
-
sum_list.append(sum1)
|
125 |
-
x=sorted(((sum_list[i],s) for i,s in enumerate(corpus)), reverse=True)
|
126 |
-
for elem in x:
|
127 |
-
final_textrank_list.append(elem[1])
|
128 |
-
|
129 |
-
################################################################ Textrank ends #################################################
|
130 |
-
|
131 |
-
######################################################## From here we start the keyphrase extraction process ################################################
|
132 |
-
|
133 |
-
a=int((10*len(final_textrank_list))/100.0)
|
134 |
-
if(a<5):
|
135 |
-
total=5
|
136 |
-
else:
|
137 |
-
total=int(a)
|
138 |
-
for i in range(total):
|
139 |
-
document.append(final_textrank_list[i])
|
140 |
-
doc=" ".join(document)
|
141 |
-
for i in document:
|
142 |
-
doc_1=nlp(i)
|
143 |
-
text_doc.append([X.text for X in doc_1.ents])
|
144 |
-
entity_list = [item for sublist in text_doc for item in sublist]
|
145 |
-
entity_list = [word for word in entity_list if not word in all_stopwords]
|
146 |
-
entity_list = [word_entity for word_entity in entity_list if(p.singular_noun(word_entity) == False)]
|
147 |
-
entity_list=list(dict.fromkeys(entity_list))
|
148 |
-
doc_embedding = model_2.encode([doc])
|
149 |
-
candidates=entity_list
|
150 |
-
candidate_embeddings = model_2.encode(candidates)
|
151 |
-
distances = cosine_similarity(doc_embedding, candidate_embeddings)
|
152 |
-
top_n = max_num_keywords
|
153 |
-
keyword_list = [candidates[index] for index in distances.argsort()[0][-top_n:]]
|
154 |
-
keywords = '\n'.join(keyword_list)
|
155 |
-
|
156 |
-
############################################################## Keyphrase extraction ends #############################################
|
157 |
-
|
158 |
-
|
159 |
-
################################################################## From here we start the clustering and query generation ##################################
|
160 |
|
161 |
-
|
162 |
-
|
163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
cl_sent_len=(len(clustered_sentences))
|
173 |
-
list_cluster=list(clustered_sentences)
|
174 |
-
a=len(list_cluster)
|
175 |
-
cluster_list_final.append(list_cluster)
|
176 |
-
if (c_len==cl_sent_len and c_len>=3) or cl_sent_len==1:
|
177 |
-
silhouette_avg = 0
|
178 |
-
silhouette_score_list.append(silhouette_avg)
|
179 |
-
elif c_len==cl_sent_len==2:
|
180 |
-
silhouette_avg = 1
|
181 |
-
silhouette_score_list.append(silhouette_avg)
|
182 |
else:
|
183 |
-
|
184 |
-
silhouette_score_list.append(silhouette_avg)
|
185 |
-
res_dict = dict(zip(silhouette_score_list, cluster_list_final))
|
186 |
-
cluster_items=res_dict[max(res_dict)]
|
187 |
-
|
188 |
-
for i in cluster_items:
|
189 |
-
z=' OR '.join(i)
|
190 |
-
comb.append("("+z+")")
|
191 |
-
comb_list.append(comb)
|
192 |
-
combinations = []
|
193 |
-
for subset in itertools.combinations(comb, 2):
|
194 |
-
combinations.append(subset)
|
195 |
-
f1_list=[]
|
196 |
-
for s in combinations:
|
197 |
-
final = ' AND '.join(s)
|
198 |
-
f1_list.append("("+final+")")
|
199 |
-
f_1=' OR '.join(f1_list)
|
200 |
-
final_list.append(f_1)
|
201 |
-
|
202 |
-
######################################################## query generation ends here #######################################
|
203 |
-
|
204 |
-
####################################### PubeMed abstract extraction starts here #########################################
|
205 |
-
|
206 |
-
ncbi_url='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/'
|
207 |
-
|
208 |
-
last_url='esearch.fcgi?db=pubmed'+'&term='+f_1
|
209 |
-
overall_url=ncbi_url+last_url+'&rettype=json'+'&sort=relevance'
|
210 |
-
pubmed_search_request = requests.get(overall_url)
|
211 |
-
|
212 |
-
root = ET.fromstring(pubmed_search_request.text)
|
213 |
-
levels = root.findall('.//Id')
|
214 |
-
search_id_list=[]
|
215 |
-
for level in levels:
|
216 |
-
name = level.text
|
217 |
-
search_id_list.append(name)
|
218 |
-
all_search_ids = ','.join(search_id_list)
|
219 |
-
fetch_url='efetch.fcgi?db=pubmed'
|
220 |
-
search_id='&id='+all_search_ids
|
221 |
-
return_url=ncbi_url+fetch_url+search_id+'&rettype=text'+'&retmode=xml'+'&retmax=500'+'&sort=relevance'
|
222 |
-
pubmed_abstract_request = requests.get(return_url)
|
223 |
-
root_1 = ET.fromstring(pubmed_abstract_request.text)
|
224 |
-
article_title = root_1.findall('.//ArticleTitle')
|
225 |
-
for a in article_title:
|
226 |
-
article_title_name = a.text
|
227 |
-
titles_list.append(article_title_name)
|
228 |
-
article_abstract = root_1.findall('.//AbstractText')
|
229 |
-
for b in article_abstract:
|
230 |
-
article_abstract_name = b.text
|
231 |
-
abstracts_list.append(article_abstract_name)
|
232 |
-
|
233 |
-
################################ PubMed extraction ends here ########################################################
|
234 |
-
|
235 |
-
########################################## Most relevant abstracts as per news article heading starts here ##########################################
|
236 |
-
|
237 |
-
first_article = Article(url, language='en')
|
238 |
-
first_article.download()
|
239 |
-
first_article.parse()
|
240 |
-
article_heading=(first_article.title)
|
241 |
-
article_heading=sent_tokenize(article_heading)
|
242 |
-
model_4 = SentenceTransformer(model_4)
|
243 |
-
|
244 |
-
my_dict = dict(zip(titles_list,abstracts_list))
|
245 |
-
title_embeddings = model_4.encode(titles_list)
|
246 |
-
heading_embedding = model_4.encode(article_heading)
|
247 |
-
similarities = cosine_similarity(heading_embedding, title_embeddings)
|
248 |
-
max_n = max_retrieved
|
249 |
-
sorted_titles = [titles_list[index] for index in similarities.argsort()[0][-max_n:]]
|
250 |
-
sorted_abstract_list=[]
|
251 |
-
for list_elem in sorted_titles:
|
252 |
-
sorted_abstract_list.append(my_dict[list_elem])
|
253 |
-
sorted_dict = {'Title': sorted_titles, 'Abstract': sorted_abstract_list}
|
254 |
-
df_new=pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in sorted_dict.items() ]))
|
255 |
-
df_final = df_new.fillna(' ')
|
256 |
-
#fp = df_final.to_csv('title_abstract.csv', index=False)
|
257 |
-
|
258 |
-
|
259 |
-
############################################# Ends here ###################################################
|
260 |
-
|
261 |
-
#return df_final
|
262 |
-
#return fp
|
263 |
-
return sorted_dict
|
264 |
-
|
265 |
|
266 |
-
igen_pubmed = gr.Interface(
|
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 |
-
article= "This work is based on the paper <a href=https://dl.acm.org/doi/10.1145/3487664.3487701>provided here</a>."
|
352 |
-
"\t It uses the TextRank algorithm with SBERT to first find the top sentences and then extracts the keyphrases from those sentences using scispaCy and SBERT."
|
353 |
-
"\t The application then uses a UMLS based BERT model, <a href=https://arxiv.org/abs/2010.11784>SapBERT</a> to cluster the keyphrases using K-means clustering method and finally create a boolean query. After that the top k titles and abstracts are retrieved from PubMed database and displayed according to relevancy. The SapBERT models can be changed as per the list provided. "
|
354 |
-
"\t The list of SBERT models required in the textboxes can be found in <a href=www.sbert.net/docs/pretrained_models.html>SBERT Pre-trained models hub</a>."
|
355 |
-
"\t The model names can be changed from the list of pre-trained models provided. "
|
356 |
-
"\t The value of keyphrases can be changed. The default value is 10, minimum is 5 and a maximum value of 20. "
|
357 |
-
"\t The value of maximum abstracts to be retrieved can be changed. The minimum is 5, default is 10 and a maximum of 15.")
|
358 |
|
359 |
-
igen_pubmed.launch(share=False,server_name='0.0.0.0',show_error=True)
|
|
|
2 |
import re
|
3 |
import nltkmodule
|
4 |
|
5 |
+
from newspaper import Article, fulltext
|
|
|
6 |
import requests
|
7 |
import itertools
|
8 |
import os
|
9 |
|
10 |
+
from nltk.tokenize import word_tokenize, sent_tokenize
|
|
|
11 |
from sentence_transformers import SentenceTransformer
|
12 |
import pandas as pd
|
13 |
import numpy as np
|
14 |
from pandas import ExcelWriter
|
15 |
from torch.utils.data import DataLoader
|
16 |
import math
|
17 |
+
from sentence_transformers import models
|
|
|
|
|
|
|
18 |
from nltk.corpus import stopwords
|
19 |
stop_words = stopwords.words('english')
|
20 |
import matplotlib.pyplot as plt
|
|
|
23 |
from sklearn.metrics.pairwise import cosine_similarity
|
24 |
import scipy.spatial
|
25 |
import networkx as nx
|
|
|
26 |
import scispacy
|
27 |
import spacy
|
28 |
import en_core_sci_lg
|
|
|
30 |
from nltk.stem.wordnet import WordNetLemmatizer
|
31 |
import gradio as gr
|
32 |
import inflect
|
33 |
+
from sklearn.metrics import silhouette_score
|
|
|
|
|
|
|
34 |
from xml.etree import ElementTree as ET
|
|
|
35 |
|
36 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
37 |
+
import torch
|
38 |
+
|
39 |
+
p = inflect.engine()
|
40 |
nlp = en_core_sci_lg.load()
|
41 |
sp = en_core_sci_lg.load()
|
42 |
all_stopwords = sp.Defaults.stop_words
|
|
|
47 |
sen_new = " ".join([i for i in sen if i not in stop_words])
|
48 |
return sen_new
|
49 |
|
50 |
+
# ------------- Evidence Extraction with NLI Model (Global Model Loading) -------------
|
51 |
+
NLI_MODEL_NAME = "pritamdeka/PubMedBERT-MNLI-MedNLI"
|
52 |
+
nli_tokenizer = AutoTokenizer.from_pretrained(NLI_MODEL_NAME)
|
53 |
+
nli_model = AutoModelForSequenceClassification.from_pretrained(NLI_MODEL_NAME)
|
54 |
+
NLI_LABELS = ['CONTRADICTION', 'NEUTRAL', 'ENTAILMENT'] # typical MNLI order
|
55 |
|
56 |
+
def extract_evidence_sentences(claim, abstracts):
|
57 |
+
results = []
|
58 |
+
for title, abstract in zip(abstracts['Title'], abstracts['Abstract']):
|
59 |
+
sentences = sent_tokenize(abstract)
|
60 |
+
evidence = []
|
61 |
+
for sent in sentences:
|
62 |
+
# premise = sent, hypothesis = claim
|
63 |
+
encoding = nli_tokenizer(
|
64 |
+
sent, claim,
|
65 |
+
return_tensors='pt',
|
66 |
+
truncation=True,
|
67 |
+
max_length=256,
|
68 |
+
padding=True
|
69 |
+
)
|
70 |
+
with torch.no_grad():
|
71 |
+
outputs = nli_model(**encoding)
|
72 |
+
probs = torch.softmax(outputs.logits, dim=1).cpu().numpy().flatten()
|
73 |
+
max_idx = probs.argmax()
|
74 |
+
label = NLI_LABELS[max_idx]
|
75 |
+
score = float(probs[max_idx])
|
76 |
+
evidence.append({
|
77 |
+
"sentence": sent,
|
78 |
+
"label": label,
|
79 |
+
"score": score
|
80 |
+
})
|
81 |
+
results.append({
|
82 |
+
"title": title,
|
83 |
+
"evidence": evidence
|
84 |
+
})
|
85 |
+
return results
|
86 |
|
87 |
+
def keyphrase_generator(
|
88 |
+
article_link, model_1, model_2, max_num_keywords, model_3, max_retrieved, model_4, extract_evidence):
|
89 |
|
90 |
+
# ---------- Robust Article Download ----------
|
91 |
+
try:
|
92 |
+
response = requests.get(article_link, timeout=20)
|
93 |
+
response.raise_for_status()
|
94 |
+
html = response.text
|
95 |
+
article = fulltext(html)
|
96 |
+
except Exception as e:
|
97 |
+
return {"error": f"Failed to download article: {str(e)}"}
|
98 |
|
99 |
+
corpus = sent_tokenize(article)
|
100 |
|
101 |
+
# ---------- TextRank + Keyphrase Extraction ----------
|
102 |
+
model_1 = SentenceTransformer(model_1)
|
103 |
+
model_2 = SentenceTransformer(model_2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
+
indicator_list = ['concluded', 'concludes', 'in a study', 'concluding', 'conclude', 'in sum', 'in a recent study',
|
106 |
+
'therefore', 'thus', 'so', 'hence', 'as a result', 'accordingly', 'consequently', 'in short',
|
107 |
+
'proves that', 'shows that', 'suggests that', 'demonstrates that', 'found that', 'observed that',
|
108 |
+
'indicated that', 'suggested that', 'demonstrated that']
|
109 |
+
score_list = []
|
110 |
+
count_dict = {}
|
111 |
+
for l in corpus:
|
112 |
+
c = 0
|
113 |
+
for l2 in indicator_list:
|
114 |
+
if l.find(l2) != -1:
|
115 |
+
c = 1
|
116 |
+
break
|
117 |
+
count_dict[l] = c
|
118 |
+
for sent, score in count_dict.items():
|
119 |
+
score_list.append(score)
|
120 |
+
clean_sentences_new = pd.Series(corpus).str.replace("[^a-zA-Z]", " ", regex=True).tolist()
|
121 |
+
corpus_embeddings = model_1.encode(clean_sentences_new)
|
122 |
+
sim_mat = np.zeros([len(clean_sentences_new), len(clean_sentences_new)])
|
123 |
+
for i in range(len(clean_sentences_new)):
|
124 |
+
len_embeddings = len(corpus_embeddings[i])
|
125 |
+
for j in range(len(clean_sentences_new)):
|
126 |
+
if i != j:
|
127 |
+
if len_embeddings == 1024:
|
128 |
+
sim_mat[i][j] = cosine_similarity(corpus_embeddings[i].reshape(1, 1024),
|
129 |
+
corpus_embeddings[j].reshape(1, 1024))[0, 0]
|
130 |
+
elif len_embeddings == 768:
|
131 |
+
sim_mat[i][j] = cosine_similarity(corpus_embeddings[i].reshape(1, 768),
|
132 |
+
corpus_embeddings[j].reshape(1, 768))[0, 0]
|
133 |
+
nx_graph = nx.from_numpy_array(sim_mat)
|
134 |
+
scores = nx.pagerank(nx_graph, max_iter=1500)
|
135 |
+
sentences = ((scores[i], s) for i, s in enumerate(corpus))
|
136 |
+
element = [elem[0] for elem in sentences]
|
137 |
+
sum_list = [sc + lst for sc, lst in zip(score_list, element)]
|
138 |
+
x = sorted(((sum_list[i], s) for i, s in enumerate(corpus)), reverse=True)
|
139 |
+
final_textrank_list = [elem[1] for elem in x]
|
140 |
+
a = int((10 * len(final_textrank_list)) / 100.0)
|
141 |
+
total = max(a, 5)
|
142 |
+
document = [final_textrank_list[i] for i in range(total)]
|
143 |
+
doc = " ".join(document)
|
144 |
+
text_doc = []
|
145 |
+
for i in document:
|
146 |
+
doc_1 = nlp(i)
|
147 |
+
text_doc.append([X.text for X in doc_1.ents])
|
148 |
+
entity_list = [item for sublist in text_doc for item in sublist]
|
149 |
+
entity_list = [word for word in entity_list if word not in all_stopwords]
|
150 |
+
entity_list = [word_entity for word_entity in entity_list if not p.singular_noun(word_entity)]
|
151 |
+
entity_list = list(dict.fromkeys(entity_list))
|
152 |
+
doc_embedding = model_2.encode([doc])
|
153 |
+
candidates = entity_list
|
154 |
+
candidate_embeddings = model_2.encode(candidates)
|
155 |
+
distances = cosine_similarity(doc_embedding, candidate_embeddings)
|
156 |
+
top_n = max_num_keywords
|
157 |
+
keyword_list = [candidates[index] for index in distances.argsort()[0][-top_n:]]
|
158 |
+
# ---------- Clustering + Query Generation ----------
|
159 |
+
word_embedding_model = models.Transformer(model_3)
|
160 |
+
pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(),
|
161 |
+
pooling_mode_mean_tokens=True,
|
162 |
+
pooling_mode_cls_token=False,
|
163 |
+
pooling_mode_max_tokens=False)
|
164 |
+
embedder = SentenceTransformer(modules=[word_embedding_model, pooling_model])
|
165 |
+
c_len = len(keyword_list)
|
166 |
+
keyword_embeddings = embedder.encode(keyword_list)
|
167 |
+
silhouette_score_list = []
|
168 |
+
cluster_list_final = []
|
169 |
+
for num_clusters in range(1, top_n):
|
170 |
+
clustering_model = KMeans(n_clusters=num_clusters)
|
171 |
+
clustering_model.fit(keyword_embeddings)
|
172 |
+
cluster_assignment = clustering_model.labels_
|
173 |
+
clustered_sentences = [[] for _ in range(num_clusters)]
|
174 |
+
for sentence_id, cluster_id in enumerate(cluster_assignment):
|
175 |
+
clustered_sentences[cluster_id].append(keyword_list[sentence_id])
|
176 |
+
cl_sent_len = len(clustered_sentences)
|
177 |
+
list_cluster = list(clustered_sentences)
|
178 |
+
cluster_list_final.append(list_cluster)
|
179 |
+
if (c_len == cl_sent_len and c_len >= 3) or cl_sent_len == 1:
|
180 |
+
silhouette_avg = 0
|
181 |
+
elif c_len == cl_sent_len == 2:
|
182 |
+
silhouette_avg = 1
|
183 |
+
else:
|
184 |
+
silhouette_avg = silhouette_score(keyword_embeddings, cluster_assignment)
|
185 |
+
silhouette_score_list.append(silhouette_avg)
|
186 |
+
res_dict = dict(zip(silhouette_score_list, cluster_list_final))
|
187 |
+
cluster_items = res_dict[max(res_dict)]
|
188 |
+
comb = []
|
189 |
+
for i in cluster_items:
|
190 |
+
z = ' OR '.join(i)
|
191 |
+
comb.append("(" + z + ")")
|
192 |
+
combinations = []
|
193 |
+
for subset in itertools.combinations(comb, 2):
|
194 |
+
combinations.append(subset)
|
195 |
+
f1_list = []
|
196 |
+
for s in combinations:
|
197 |
+
final = ' AND '.join(s)
|
198 |
+
f1_list.append("(" + final + ")")
|
199 |
+
f_1 = ' OR '.join(f1_list)
|
200 |
+
# ---------- PubMed Abstract Extraction ----------
|
201 |
+
ncbi_url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/'
|
202 |
+
last_url = 'esearch.fcgi?db=pubmed' + '&term=' + f_1
|
203 |
+
overall_url = ncbi_url + last_url + '&rettype=json' + '&sort=relevance'
|
204 |
+
try:
|
205 |
+
pubmed_search_request = requests.get(overall_url, timeout=20)
|
206 |
+
root = ET.fromstring(pubmed_search_request.text)
|
207 |
+
levels = root.findall('.//Id')
|
208 |
+
search_id_list = [level.text for level in levels]
|
209 |
+
if not search_id_list:
|
210 |
+
return {"error": "No PubMed results found."}
|
211 |
+
except Exception as e:
|
212 |
+
return {"error": f"Error retrieving from PubMed: {str(e)}"}
|
213 |
+
all_search_ids = ','.join(search_id_list)
|
214 |
+
fetch_url = 'efetch.fcgi?db=pubmed'
|
215 |
+
search_id = '&id=' + all_search_ids
|
216 |
+
return_url = ncbi_url + fetch_url + search_id + '&rettype=text' + '&retmode=xml' + '&retmax=500' + '&sort=relevance'
|
217 |
+
try:
|
218 |
+
pubmed_abstract_request = requests.get(return_url, timeout=20)
|
219 |
+
root_1 = ET.fromstring(pubmed_abstract_request.text)
|
220 |
+
article_title = root_1.findall('.//ArticleTitle')
|
221 |
+
titles_list = [a.text for a in article_title]
|
222 |
+
article_abstract = root_1.findall('.//AbstractText')
|
223 |
+
abstracts_list = [b.text for b in article_abstract]
|
224 |
+
except Exception as e:
|
225 |
+
return {"error": f"Error extracting PubMed abstracts: {str(e)}"}
|
226 |
+
if not titles_list or not abstracts_list:
|
227 |
+
return {"error": "No abstracts found for this query."}
|
228 |
+
# ---------- Most relevant abstracts by heading ----------
|
229 |
+
try:
|
230 |
+
first_article = Article(article_link, language='en')
|
231 |
+
first_article.download()
|
232 |
+
first_article.parse()
|
233 |
+
article_heading = first_article.title
|
234 |
+
if not article_heading or not isinstance(article_heading, str):
|
235 |
+
article_heading = corpus[0] if corpus else ""
|
236 |
+
except Exception:
|
237 |
+
article_heading = corpus[0] if corpus else ""
|
238 |
+
model_4 = SentenceTransformer(model_4)
|
239 |
+
my_dict = dict(zip(titles_list, abstracts_list))
|
240 |
+
title_embeddings = model_4.encode(titles_list)
|
241 |
+
heading_embedding = model_4.encode([article_heading])
|
242 |
+
similarities = cosine_similarity(heading_embedding, title_embeddings)
|
243 |
+
max_n = max_retrieved
|
244 |
+
sorted_titles = [titles_list[index] for index in similarities.argsort()[0][-max_n:]]
|
245 |
+
sorted_abstract_list = [my_dict[list_elem] for list_elem in sorted_titles]
|
246 |
+
sorted_dict = {'Title': sorted_titles, 'Abstract': sorted_abstract_list}
|
247 |
|
248 |
+
# ---------- Evidence Extraction Integration ----------
|
249 |
+
if extract_evidence:
|
250 |
+
evidence_results = extract_evidence_sentences(
|
251 |
+
article_heading,
|
252 |
+
sorted_dict,
|
253 |
+
)
|
254 |
+
return evidence_results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
255 |
else:
|
256 |
+
return sorted_dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
257 |
|
258 |
+
igen_pubmed = gr.Interface(
|
259 |
+
keyphrase_generator,
|
260 |
+
inputs=[
|
261 |
+
gr.components.Textbox(lines=1, placeholder="Provide article web link here", value="", label="Article web link"),
|
262 |
+
gr.components.Dropdown(
|
263 |
+
choices=[
|
264 |
+
'sentence-transformers/all-mpnet-base-v2',
|
265 |
+
'sentence-transformers/all-mpnet-base-v1',
|
266 |
+
'sentence-transformers/all-distilroberta-v1',
|
267 |
+
'sentence-transformers/gtr-t5-large',
|
268 |
+
'pritamdeka/S-Bluebert-snli-multinli-stsb',
|
269 |
+
'pritamdeka/S-Biomed-Roberta-snli-multinli-stsb',
|
270 |
+
'pritamdeka/S-BioBert-snli-multinli-stsb',
|
271 |
+
'sentence-transformers/stsb-mpnet-base-v2',
|
272 |
+
'sentence-transformers/stsb-roberta-base-v2',
|
273 |
+
'sentence-transformers/stsb-distilroberta-base-v2',
|
274 |
+
'sentence-transformers/sentence-t5-large',
|
275 |
+
'sentence-transformers/sentence-t5-base'
|
276 |
+
],
|
277 |
+
type="value",
|
278 |
+
value='sentence-transformers/stsb-roberta-base-v2',
|
279 |
+
label="Select any SBERT model for TextRank"
|
280 |
+
),
|
281 |
+
gr.components.Dropdown(
|
282 |
+
choices=[
|
283 |
+
'sentence-transformers/paraphrase-mpnet-base-v2',
|
284 |
+
'sentence-transformers/all-mpnet-base-v1',
|
285 |
+
'sentence-transformers/paraphrase-distilroberta-base-v1',
|
286 |
+
'sentence-transformers/paraphrase-xlm-r-multilingual-v1',
|
287 |
+
'sentence-transformers/paraphrase-multilingual-mpnet-base-v2',
|
288 |
+
'sentence-transformers/paraphrase-albert-small-v2',
|
289 |
+
'sentence-transformers/paraphrase-albert-base-v2',
|
290 |
+
'sentence-transformers/paraphrase-MiniLM-L12-v2',
|
291 |
+
'sentence-transformers/paraphrase-MiniLM-L6-v2',
|
292 |
+
'sentence-transformers/all-MiniLM-L12-v2',
|
293 |
+
'sentence-transformers/all-distilroberta-v1',
|
294 |
+
'sentence-transformers/paraphrase-TinyBERT-L6-v2',
|
295 |
+
'sentence-transformers/paraphrase-MiniLM-L3-v2',
|
296 |
+
'sentence-transformers/all-MiniLM-L6-v2'
|
297 |
+
],
|
298 |
+
type="value",
|
299 |
+
value='sentence-transformers/all-mpnet-base-v1',
|
300 |
+
label="Select any SBERT model for keyphrases"
|
301 |
+
),
|
302 |
+
gr.components.Slider(minimum=5, maximum=20, step=1, value=10, label="Max Keywords"),
|
303 |
+
gr.components.Dropdown(
|
304 |
+
choices=[
|
305 |
+
'cambridgeltl/SapBERT-from-PubMedBERT-fulltext',
|
306 |
+
'cambridgeltl/SapBERT-from-PubMedBERT-fulltext-mean-token'
|
307 |
+
],
|
308 |
+
type="value",
|
309 |
+
value='cambridgeltl/SapBERT-from-PubMedBERT-fulltext',
|
310 |
+
label="Select any SapBERT model for clustering"
|
311 |
+
),
|
312 |
+
gr.components.Slider(minimum=5, maximum=15, step=1, value=10, label="PubMed Max Abstracts"),
|
313 |
+
gr.components.Dropdown(
|
314 |
+
choices=[
|
315 |
+
'pritamdeka/S-Bluebert-snli-multinli-stsb',
|
316 |
+
'pritamdeka/S-BioBert-snli-multinli-stsb',
|
317 |
+
'pritamdeka/S-Biomed-Roberta-snli-multinli-stsb',
|
318 |
+
'sentence-transformers/all-mpnet-base-v2'
|
319 |
+
],
|
320 |
+
type="value",
|
321 |
+
value='sentence-transformers/all-mpnet-base-v2',
|
322 |
+
label="Select any SBERT model for abstracts"
|
323 |
+
),
|
324 |
+
gr.components.Checkbox(label="Enable Evidence Extraction", value=True)
|
325 |
+
],
|
326 |
+
outputs=gr.components.JSON(label="Results (Abstracts + Evidence)"),
|
327 |
+
title="PubMed Abstract Retriever",
|
328 |
+
description="Retrieves relevant PubMed abstracts for an online article and optionally extracts evidence for the claim made in the article headline. Outputs JSON mapping each abstract to evidence sentences and their stance (ENTAILMENT/SUPPORT, CONTRADICTION, NEUTRAL).",
|
329 |
+
examples=[
|
330 |
+
[
|
331 |
+
"https://www.cancer.news/2021-12-22-mrna-vaccines-weaken-immune-system-cause-cancer.html",
|
332 |
+
'sentence-transformers/all-mpnet-base-v1',
|
333 |
+
'sentence-transformers/paraphrase-MiniLM-L12-v2',
|
334 |
+
10,
|
335 |
+
'cambridgeltl/SapBERT-from-PubMedBERT-fulltext',
|
336 |
+
15,
|
337 |
+
'pritamdeka/S-Biomed-Roberta-snli-multinli-stsb',
|
338 |
+
True
|
339 |
+
]
|
340 |
+
]
|
341 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
342 |
|
343 |
+
igen_pubmed.launch(share=False, server_name='0.0.0.0', show_error=True)
|