Update app.py
Browse files
app.py
CHANGED
@@ -1,507 +1,511 @@
|
|
1 |
-
import pandas as pd
|
2 |
-
import json
|
3 |
-
import numpy as np
|
4 |
-
import re
|
5 |
-
from itertools import combinations as itertools_combinations
|
6 |
-
import os
|
7 |
-
import sys
|
8 |
-
from SPARQLWrapper import SPARQLWrapper, JSON
|
9 |
-
from sentence_transformers import SentenceTransformer
|
10 |
-
import aiohttp
|
11 |
-
import asyncio
|
12 |
-
import streamlit as st
|
13 |
-
import time
|
14 |
-
from openai import OpenAI
|
15 |
-
import sys
|
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 |
-
async def
|
50 |
-
async with
|
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 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
{
|
389 |
-
"role": "
|
390 |
-
"content":
|
391 |
-
}
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
|
|
|
|
|
|
|
|
507 |
main_cli()
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import json
|
3 |
+
import numpy as np
|
4 |
+
import re
|
5 |
+
from itertools import combinations as itertools_combinations
|
6 |
+
import os
|
7 |
+
import sys
|
8 |
+
from SPARQLWrapper import SPARQLWrapper, JSON
|
9 |
+
from sentence_transformers import SentenceTransformer
|
10 |
+
import aiohttp
|
11 |
+
import asyncio
|
12 |
+
import streamlit as st
|
13 |
+
import time
|
14 |
+
from openai import OpenAI
|
15 |
+
import sys
|
16 |
+
|
17 |
+
new_directory = "info_extraction"
|
18 |
+
if not os.path.exists(new_directory):
|
19 |
+
os.makedirs(new_directory)
|
20 |
+
|
21 |
+
model = SentenceTransformer("Lajavaness/bilingual-embedding-large", trust_remote_code=True)
|
22 |
+
|
23 |
+
token = os.environ["GITHUB_TOKEN"]
|
24 |
+
endpoint = "https://models.inference.ai.azure.com"
|
25 |
+
model_name = "gpt-4o"
|
26 |
+
|
27 |
+
client = OpenAI(
|
28 |
+
base_url=endpoint,
|
29 |
+
api_key=token,
|
30 |
+
)
|
31 |
+
|
32 |
+
|
33 |
+
async def fetch_url(session, url):
|
34 |
+
pageids_list = []
|
35 |
+
async with session.get(url) as response:
|
36 |
+
x = await response.text()
|
37 |
+
objective_list = x.split('"objectiveResults\\":')[-1].split(',\\"wikipediaResults\\"')[0].replace('\\\\\\"', "").replace("\\", "")
|
38 |
+
wikipedia_list = x.split(',\\"wikipediaResults\\":')[-1].split(',\\"data-sentry-element\\"')[0].replace('\\\\\\"', "").replace("\\", "")
|
39 |
+
data_1 = json.loads(objective_list)
|
40 |
+
data_2 = json.loads(wikipedia_list)
|
41 |
+
for i in data_1:
|
42 |
+
pageids_list.append(i.get("page_id"))
|
43 |
+
for i in data_2:
|
44 |
+
pageids_list.append(i.get("pageid"))
|
45 |
+
print(pageids_list)
|
46 |
+
return pageids_list
|
47 |
+
|
48 |
+
|
49 |
+
async def fetch_json(url, session):
|
50 |
+
async with session.get(url) as response:
|
51 |
+
return await response.json()
|
52 |
+
|
53 |
+
async def combination_method(name, session):
|
54 |
+
async with aiohttp.ClientSession() as session:
|
55 |
+
data = set()
|
56 |
+
new_name = name.replace("+", " ").split()
|
57 |
+
x = itertools_combinations(new_name, 2)
|
58 |
+
for i in x:
|
59 |
+
new_word = (i[0] + " " + i[1]).replace(" ", "+")
|
60 |
+
url = f"https://www.objective.inc/demos/wikipedia?query={new_word}"
|
61 |
+
page_source = await fetch_url(session, url)
|
62 |
+
for i in page_source:
|
63 |
+
data.add(i)
|
64 |
+
return data
|
65 |
+
|
66 |
+
async def single_method(name, session):
|
67 |
+
async with aiohttp.ClientSession() as session:
|
68 |
+
data = set()
|
69 |
+
new_name = name.replace("+", " ").replace("-", " ").replace("/", " ").split()
|
70 |
+
for i in new_name:
|
71 |
+
new_word = i.replace(" ", "+")
|
72 |
+
url = f"https://www.objective.inc/demos/wikipedia?query={new_word}"
|
73 |
+
page_source = await fetch_url(session, url)
|
74 |
+
for i in page_source:
|
75 |
+
data.add(i)
|
76 |
+
return data
|
77 |
+
|
78 |
+
async def mains(name, single, combi):
|
79 |
+
data = set()
|
80 |
+
disam_data = set()
|
81 |
+
qids = set()
|
82 |
+
|
83 |
+
async with aiohttp.ClientSession() as session:
|
84 |
+
url = f"https://www.objective.inc/demos/wikipedia?query={name}"
|
85 |
+
page_source = await fetch_url(session, url)
|
86 |
+
for i in page_source:
|
87 |
+
data.add(i)
|
88 |
+
|
89 |
+
wikipedia_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={name}&srlimit=1&srprop=&srenablerewrites=True&srinfo=suggestion&format=json"
|
90 |
+
json_data = await fetch_json(wikipedia_url, session)
|
91 |
+
suggestion = json_data.get('query', {}).get('searchinfo', {}).get('suggestion')
|
92 |
+
|
93 |
+
if suggestion:
|
94 |
+
suggested_url = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={suggestion}&srlimit=10&srprop=&srenablerewrites=True&srinfo=suggestion&format=json"
|
95 |
+
json_suggestion = await fetch_json(suggested_url, session)
|
96 |
+
results = json_suggestion.get('query', {}).get('search')
|
97 |
+
for i in results:
|
98 |
+
data.add(int(i.get('pageid')))
|
99 |
+
|
100 |
+
# Handle disambiguation links
|
101 |
+
if data != {0}:
|
102 |
+
for ids in data:
|
103 |
+
titles = set()
|
104 |
+
wikipedia_disambiguation = f"https://en.wikipedia.org/w/api.php?action=query&generator=links&format=json&redirects=1&pageids={ids}&prop=pageprops&gpllimit=50&ppprop=wikibase_item"
|
105 |
+
json_id = await fetch_json(wikipedia_disambiguation, session)
|
106 |
+
try:
|
107 |
+
title = json_id.get('query').get('pages')
|
108 |
+
for k, v in title.items():
|
109 |
+
titles.add(v.get("title"))
|
110 |
+
except:
|
111 |
+
pass
|
112 |
+
|
113 |
+
if "Help:Disambiguation" in titles:
|
114 |
+
for i in titles:
|
115 |
+
if ":" not in i:
|
116 |
+
wikipedia_disamb = f"https://en.wikipedia.org/w/api.php?action=query&format=json&titles={i}&indexpageids"
|
117 |
+
json_id = await fetch_json(wikipedia_disamb, session)
|
118 |
+
real_title = json_id.get('query').get('pageids')
|
119 |
+
disam_data.add(int(real_title[0]))
|
120 |
+
else:
|
121 |
+
disam_data.add(ids)
|
122 |
+
|
123 |
+
# Makes combinations of the name
|
124 |
+
if combi == "Yes":
|
125 |
+
if len(name.replace("+", " ").replace("-", " ").split()) >= 3:
|
126 |
+
combination_names = await combination_method(name, session)
|
127 |
+
for i in combination_names:
|
128 |
+
disam_data.add(i)
|
129 |
+
|
130 |
+
# Checks every word alone
|
131 |
+
if single == "Yes":
|
132 |
+
if len(name.replace("+", " ").replace("-", " ").replace("/", " ").split()) >= 2:
|
133 |
+
singles = await single_method(name, session)
|
134 |
+
for i in singles:
|
135 |
+
disam_data.add(i)
|
136 |
+
|
137 |
+
for ids in disam_data:
|
138 |
+
try:
|
139 |
+
wikibase_url = f"https://en.wikipedia.org/w/api.php?action=query&pageids={ids}&prop=pageprops&format=json"
|
140 |
+
json_qid = await fetch_json(wikibase_url, session)
|
141 |
+
wikidata_qid = json_qid.get('query', {}).get('pages', {}).get(str(ids), {}).get('pageprops', {}).get('wikibase_item', {})
|
142 |
+
if wikidata_qid:
|
143 |
+
qids.add(wikidata_qid)
|
144 |
+
except:
|
145 |
+
pass
|
146 |
+
|
147 |
+
# Save QIDs to file
|
148 |
+
with open(f"qids_folder/{name}.json", "w") as f:
|
149 |
+
json.dump(list(qids), f)
|
150 |
+
|
151 |
+
|
152 |
+
async def get_results(query):
|
153 |
+
user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
|
154 |
+
url = "https://query.wikidata.org/sparql"
|
155 |
+
sparql = SPARQLWrapper(url, agent=user_agent)
|
156 |
+
sparql.setQuery(query)
|
157 |
+
sparql.setReturnFormat(JSON)
|
158 |
+
return sparql.query().convert()
|
159 |
+
|
160 |
+
def get_resultss(query):
|
161 |
+
user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
|
162 |
+
url = "https://query.wikidata.org/sparql"
|
163 |
+
sparql = SPARQLWrapper(url, agent=user_agent)
|
164 |
+
sparql.setQuery(query)
|
165 |
+
sparql.setReturnFormat(JSON)
|
166 |
+
return sparql.query().convert()
|
167 |
+
|
168 |
+
|
169 |
+
def cleaner(text):
|
170 |
+
text = text.replace('\\', '').replace('\n', ' ')
|
171 |
+
text = re.sub(r'\{.*?\}', '', text)
|
172 |
+
text = re.sub(' +', ' ', text).strip()
|
173 |
+
return text
|
174 |
+
|
175 |
+
async def retriever(qid):
|
176 |
+
async with aiohttp.ClientSession() as session:
|
177 |
+
list_with_sent = []
|
178 |
+
|
179 |
+
query_label = f"""SELECT ?subjectLabel
|
180 |
+
WHERE {{
|
181 |
+
wd:{qid} rdfs:label ?subjectLabel .
|
182 |
+
FILTER(LANG(?subjectLabel) = "en")
|
183 |
+
}}
|
184 |
+
"""
|
185 |
+
|
186 |
+
results = await get_results(query_label)
|
187 |
+
|
188 |
+
label = None
|
189 |
+
if results["results"]["bindings"]:
|
190 |
+
for result in results["results"]["bindings"]:
|
191 |
+
for key, value in result.items():
|
192 |
+
label = value.get("value", {}).lower() # Get label and convert to lower case
|
193 |
+
|
194 |
+
query_alias = f"""SELECT ?alias
|
195 |
+
WHERE {{
|
196 |
+
wd:{qid} skos:altLabel ?alias
|
197 |
+
FILTER(LANG(?alias) = "en")
|
198 |
+
}}
|
199 |
+
"""
|
200 |
+
|
201 |
+
alias_list = []
|
202 |
+
results = await get_results(query_alias)
|
203 |
+
|
204 |
+
for result in results["results"]["bindings"]:
|
205 |
+
for key, value in result.items():
|
206 |
+
alias = value.get("value", "None")
|
207 |
+
alias_list.append(alias)
|
208 |
+
|
209 |
+
query_desci = f"""SELECT ?subjectLabel
|
210 |
+
WHERE {{
|
211 |
+
?subjectLabel schema:about wd:{qid} ;
|
212 |
+
schema:inLanguage "en" ;
|
213 |
+
schema:isPartOf <https://en.wikipedia.org/> .
|
214 |
+
}}
|
215 |
+
"""
|
216 |
+
|
217 |
+
results = await get_results(query_desci)
|
218 |
+
cleaned_first_para = "None"
|
219 |
+
|
220 |
+
if results["results"]["bindings"]:
|
221 |
+
for result in results["results"]["bindings"]:
|
222 |
+
for key, value in result.items():
|
223 |
+
desc = value.get("value", "None")
|
224 |
+
|
225 |
+
title = desc.split("/wiki/")[1]
|
226 |
+
|
227 |
+
url = f"https://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles={title}&exintro=&exsentences=2&explaintext=&redirects=&formatversion=2&format=json"
|
228 |
+
|
229 |
+
|
230 |
+
json_data = await fetch_json(url, session)
|
231 |
+
cleaned_first_para = cleaner(json_data.get('query', {}).get('pages', [{}])[0].get('extract', 'None'))
|
232 |
+
else:
|
233 |
+
query_desc = f"""SELECT ?subjectLabel
|
234 |
+
WHERE {{
|
235 |
+
wd:{qid} schema:description ?subjectLabel .
|
236 |
+
FILTER(LANG(?subjectLabel) = "en")
|
237 |
+
}}
|
238 |
+
"""
|
239 |
+
|
240 |
+
results = await get_results(query_desc)
|
241 |
+
if results["results"]["bindings"]:
|
242 |
+
for result in results["results"]["bindings"]:
|
243 |
+
for key, value in result.items():
|
244 |
+
cleaned_first_para = value.get("value", "None")
|
245 |
+
|
246 |
+
list_with_sent.append({"qid": qid, "label": label, "description": cleaned_first_para})
|
247 |
+
|
248 |
+
if alias_list:
|
249 |
+
for alias in alias_list:
|
250 |
+
list_with_sent.append({"qid": qid, "label": alias.lower(), "description": cleaned_first_para})
|
251 |
+
|
252 |
+
return list_with_sent
|
253 |
+
|
254 |
+
# Main async function to handle multiple QIDs with batching
|
255 |
+
async def main(name):
|
256 |
+
with open(f"qids_folder/{name}.json", "r") as f:
|
257 |
+
final_list = []
|
258 |
+
qids = json.load(f)
|
259 |
+
for q in qids:
|
260 |
+
returned_list = await retriever(q)
|
261 |
+
if returned_list:
|
262 |
+
final_list.extend(returned_list)
|
263 |
+
|
264 |
+
with open(f"info_extraction/{name}.json", "w", encoding="utf-8") as flast:
|
265 |
+
json.dump(final_list, flast)
|
266 |
+
|
267 |
+
def check_sentence(sentence):
|
268 |
+
two_consecutive_uppercase = r"[A-Z]{2}"
|
269 |
+
uppercase_followed_by_fullstop = r"[A-Z]\."
|
270 |
+
|
271 |
+
if re.search(two_consecutive_uppercase, sentence):
|
272 |
+
return True
|
273 |
+
|
274 |
+
if re.search(uppercase_followed_by_fullstop, sentence):
|
275 |
+
return True
|
276 |
+
|
277 |
+
return False
|
278 |
+
|
279 |
+
chrome_driver_path = "chromedriver.exe"
|
280 |
+
chrome_path = r'"C:\Program Files\Google\Chrome\Application\chrome.exe"'
|
281 |
+
|
282 |
+
def main_cli():
|
283 |
+
st.title("✨ Entity Linking Application ✨")
|
284 |
+
st.caption("This Web Application is part of my master dissertation.")
|
285 |
+
|
286 |
+
|
287 |
+
input_sentence_user = st.text_input("Enter the sentence:", "")
|
288 |
+
input_mention_user = st.text_input("Enter the mention:", "")
|
289 |
+
single = st.selectbox("Search each word individually?", ['Yes', 'No'], index=1)
|
290 |
+
combi = st.selectbox("Make combinations of each word?", ['Yes', 'No'], index=1)
|
291 |
+
disambi = st.selectbox("Run acronym disambiguation? (Enable it if the mention is nested)", ['Yes', 'No'], index=0)
|
292 |
+
|
293 |
+
|
294 |
+
if st.button("Run Entity Linking"):
|
295 |
+
if input_sentence_user and input_mention_user:
|
296 |
+
# Example logic: check if the mention is in the sentence
|
297 |
+
if input_mention_user in input_sentence_user:
|
298 |
+
st.write("Applying Data Normalization module... (1/5)")
|
299 |
+
# Data Normalization
|
300 |
+
|
301 |
+
start_time = time.time()
|
302 |
+
|
303 |
+
list_with_full_names = []
|
304 |
+
list_with_names_to_show = []
|
305 |
+
|
306 |
+
if disambi == "Yes":
|
307 |
+
response = client.chat.completions.create(
|
308 |
+
messages=[
|
309 |
+
{
|
310 |
+
"role": "system",
|
311 |
+
"content": """
|
312 |
+
I will give you one or more labels within a sentence. Your task is as follows:
|
313 |
+
|
314 |
+
Identify each label in the sentence, and check if it is an acronym.
|
315 |
+
|
316 |
+
If the label is an acronym, respond with the full name of the acronym.
|
317 |
+
If the label is not an acronym, respond with the label exactly as it was given to you.
|
318 |
+
If a label contains multiple terms (e.g., 'phase and DIC microscopy'), treat each term within the label as a separate label.
|
319 |
+
|
320 |
+
This means you should identify and explain each part of the label individually.
|
321 |
+
Each part should be on its own line in the response.
|
322 |
+
Context-Specific Terms: If the sentence context suggests a relevant term that applies to each label (such as "study" in 'morphological, sedimentological, and stratigraphical study'), add that term to each label’s explanation.
|
323 |
+
|
324 |
+
Use context clues to determine the appropriate term to add (e.g., 'study' or 'microscopy').
|
325 |
+
Output Format: Your response should contain only the explanations, formatted as follows:
|
326 |
+
|
327 |
+
Each label or part of a label should be on a new line.
|
328 |
+
Do not include any additional text, and do not repeat the original sentence.
|
329 |
+
Example 1:
|
330 |
+
|
331 |
+
Input:
|
332 |
+
|
333 |
+
label: phase and DIC microscopy
|
334 |
+
context: Tardigrades have been extracted from samples using centrifugation with Ludox AM™ and mounted on individual microscope slides in Hoyer's medium for identification under phase and DIC microscopy.
|
335 |
+
Expected response:
|
336 |
+
|
337 |
+
phase: phase microscopy
|
338 |
+
DIC microscopy: Differential interference contrast microscopy
|
339 |
+
Example 2:
|
340 |
+
|
341 |
+
Input:
|
342 |
+
|
343 |
+
label: morphological, sedimentological, and stratigraphical study
|
344 |
+
context: This paper presents results of a morphological, sedimentological, and stratigraphical study of relict beach ridges formed on a prograded coastal barrier in Bream Bay, North Island New Zealand.
|
345 |
+
Expected response:
|
346 |
+
|
347 |
+
morphological: morphological study
|
348 |
+
sedimentological: sedimentological study
|
349 |
+
stratigraphical: stratigraphical study
|
350 |
+
IMPORTANT:
|
351 |
+
|
352 |
+
Each label, even if nested within another, should be treated as an individual item.
|
353 |
+
Each individual label or acronym should be output on a separate line.
|
354 |
+
"""
|
355 |
+
},
|
356 |
+
{
|
357 |
+
"role": "user",
|
358 |
+
"content": f"label:{input_mention_user}, context:{input_sentence_user}"
|
359 |
+
}
|
360 |
+
],
|
361 |
+
temperature=1.0,
|
362 |
+
top_p=1.0,
|
363 |
+
max_tokens=1000,
|
364 |
+
model=model_name
|
365 |
+
)
|
366 |
+
|
367 |
+
print(response.choices[0].message.content)
|
368 |
+
|
369 |
+
kati = response.choices[0].message.content.splitlines()
|
370 |
+
|
371 |
+
for i in kati:
|
372 |
+
context = i.split(":")[-1].strip()
|
373 |
+
original_name = i.split(":")[0].strip()
|
374 |
+
list_with_full_names.append(context)
|
375 |
+
list_with_names_to_show.append(original_name)
|
376 |
+
|
377 |
+
name = ",".join(list_with_full_names)
|
378 |
+
|
379 |
+
else:
|
380 |
+
name = input_mention_user
|
381 |
+
list_with_full_names.append(name)
|
382 |
+
list_with_names_to_show.append(name)
|
383 |
+
|
384 |
+
input_sentence_user = input_sentence_user.replace(input_mention_user, name) # Changing the mention to the correct one
|
385 |
+
|
386 |
+
response = client.chat.completions.create(
|
387 |
+
messages=[
|
388 |
+
{
|
389 |
+
"role": "system",
|
390 |
+
"content": "Given a label or labels within a sentence, provide a brief description (2-3 sentences) explaining what the label represents, similar to how a Wikipedia entry would. Format your response as follows: label: description. I want only the description of the label, not the role in the context. Include the label in the description as well. For example: Sentiment analysis: Sentiment analysis is the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information.\nText analysis: Text mining, text data mining (TDM) or text analytics is the process of deriving high-quality information from text. It involves the discovery by computer of new, previously unknown information, by automatically extracting information from different written resources.",
|
391 |
+
},
|
392 |
+
{
|
393 |
+
"role": "user",
|
394 |
+
"content": f"label:{name}, context:{input_sentence_user}"
|
395 |
+
}
|
396 |
+
],
|
397 |
+
temperature=1.0,
|
398 |
+
top_p=1.0,
|
399 |
+
max_tokens=1000,
|
400 |
+
model=model_name
|
401 |
+
)
|
402 |
+
|
403 |
+
print(response.choices[0].message.content)
|
404 |
+
|
405 |
+
z = response.choices[0].message.content.splitlines()
|
406 |
+
list_with_contexts = []
|
407 |
+
for i in z:
|
408 |
+
context = i.split(":")[-1].strip()
|
409 |
+
list_with_contexts.append(context)
|
410 |
+
|
411 |
+
# Candidate Generation & Information Extraction
|
412 |
+
async def big_main(mention, single, combi):
|
413 |
+
mention = mention.split(",")
|
414 |
+
st.write("Applying Candidate Generation module... (2/5)")
|
415 |
+
for i in mention:
|
416 |
+
await mains(i, single, combi)
|
417 |
+
st.write("Applying Information Extraction module... (3/5)")
|
418 |
+
for i in mention:
|
419 |
+
await main(i)
|
420 |
+
|
421 |
+
asyncio.run(big_main(name, single, combi))
|
422 |
+
|
423 |
+
number = 0
|
424 |
+
for i,j,o in zip(list_with_full_names,list_with_contexts,list_with_names_to_show):
|
425 |
+
number += 1
|
426 |
+
st.write(f"Applying Candidate Selection module... (4/5) [{number}/{len(list_with_full_names)}]")
|
427 |
+
with open(f"info_extraction/{i}.json", "r") as f:
|
428 |
+
json_file = json.load(f)
|
429 |
+
lista = []
|
430 |
+
lista_1 = []
|
431 |
+
for element in json_file:
|
432 |
+
qid = element.get("qid")
|
433 |
+
link = f"https://www.wikidata.org/wiki/{qid}"
|
434 |
+
label = element.get("label")
|
435 |
+
description = element.get("description")
|
436 |
+
|
437 |
+
label_emb = model.encode([label])
|
438 |
+
desc_emb = model.encode([description])
|
439 |
+
|
440 |
+
lista.append({link: [label_emb, desc_emb]})
|
441 |
+
|
442 |
+
label_dataset_emb = model.encode([i])
|
443 |
+
desc_dataset_emb = model.encode([j])
|
444 |
+
|
445 |
+
for emb in lista:
|
446 |
+
for k, v in emb.items():
|
447 |
+
cossim_label = model.similarity(label_dataset_emb, v[0][0])
|
448 |
+
desc_label = model.similarity(desc_dataset_emb, v[1][0])
|
449 |
+
emb_mean = np.mean([cossim_label, desc_label])
|
450 |
+
lista_1.append({k: emb_mean})
|
451 |
+
|
452 |
+
sorted_data = sorted(lista_1, key=lambda x: list(x.values())[0], reverse=True)
|
453 |
+
st.write(f"Applying Entity Linking module... (4/5) [{number}/{len(list_with_full_names)}]")
|
454 |
+
if sorted_data:
|
455 |
+
sorted_top = sorted_data[0]
|
456 |
+
for k, v in sorted_top.items():
|
457 |
+
qid = k.split("/")[-1]
|
458 |
+
|
459 |
+
wikidata2wikipedia = f"""
|
460 |
+
SELECT ?wikipedia
|
461 |
+
WHERE {{
|
462 |
+
?wikipedia schema:about wd:{qid} .
|
463 |
+
?wikipedia schema:isPartOf <https://en.wikipedia.org/> .
|
464 |
+
}}
|
465 |
+
"""
|
466 |
+
results = get_resultss(wikidata2wikipedia)
|
467 |
+
|
468 |
+
for result in results["results"]["bindings"]:
|
469 |
+
for key, value in result.items():
|
470 |
+
wikipedia = value.get("value", "None")
|
471 |
+
|
472 |
+
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
|
473 |
+
wikidata2dbpedia = f"""
|
474 |
+
SELECT ?dbpedia
|
475 |
+
WHERE {{
|
476 |
+
?dbpedia owl:sameAs <http://www.wikidata.org/entity/{qid}>.
|
477 |
+
}}
|
478 |
+
"""
|
479 |
+
sparql.setQuery(wikidata2dbpedia)
|
480 |
+
sparql.setReturnFormat(JSON)
|
481 |
+
results = sparql.query().convert()
|
482 |
+
for result in results["results"]["bindings"]:
|
483 |
+
dbpedia = result["dbpedia"]["value"]
|
484 |
+
|
485 |
+
st.text(f"The correct entity for '{o}' is:")
|
486 |
+
st.success(f"Wikipedia: {wikipedia}")
|
487 |
+
st.success(f"Wikidata: {k}")
|
488 |
+
st.success(f"DBpedia: {dbpedia}")
|
489 |
+
else:
|
490 |
+
st.warning(f"The entity: {o} is NIL.")
|
491 |
+
else:
|
492 |
+
st.warning(f"The mention '{input_mention_user}' was NOT found in the sentence.")
|
493 |
+
else:
|
494 |
+
st.warning("Please fill in both fields.")
|
495 |
+
end_time = time.time()
|
496 |
+
execution_time = end_time - start_time
|
497 |
+
ETA = time.strftime("%H:%M:%S", time.gmtime(execution_time))
|
498 |
+
st.write(f"Execution time: {ETA}")
|
499 |
+
|
500 |
+
folder_path = "qids_folder"
|
501 |
+
for filename in os.listdir(folder_path):
|
502 |
+
file_path = os.path.join(folder_path, filename)
|
503 |
+
os.remove(file_path)
|
504 |
+
|
505 |
+
folder_path_1 = "info_extraction"
|
506 |
+
for filename in os.listdir(folder_path_1):
|
507 |
+
file_path = os.path.join(folder_path_1, filename)
|
508 |
+
os.remove(file_path)
|
509 |
+
|
510 |
+
if __name__ == "__main__":
|
511 |
main_cli()
|