-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpureImages.py
executable file
·285 lines (252 loc) · 12.2 KB
/
pureImages.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
import os
import shutil
import time
import itertools
import re
import nltk
from nltk import ne_chunk, pos_tag, word_tokenize
from nltk.corpus import wordnet
from nltk.tree import Tree
import requests
from bs4 import BeautifulSoup
import entityEtra
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
relationToUse = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
mainSim, hashOut = 0, 0
subToUse, objToUse = '', ''
def calSimilarity(subject, object, writer, sub1, sub2, context):
global mainSim
global hashOut
try:
rel = requests.get('http://api.conceptnet.io/query?node=/c/en/{}&other=/c/en/{}'.format(subject, object)).json()
relation = rel['edges'][0]['@id'].split('/')[4]
s = "/".join(sub1.split('/')[:-1])
o = "/".join(sub2.split('/')[:-1])
writer.write(
'<{}> <{}{}> <{}> <{}> .'.format(s + '/' +subject.capitalize(), relationToUse, relation, o +'/' + object.capitalize(),
context))
writer.write("\n")
except Exception as e:
pass
else:
# print("NO error")
try:
Similarity = requests.get(
'http://api.conceptnet.io/related/c/en/{}?filter=/c/en/{}'.format(subject, object)).json()
Similarity = Similarity['related'][0]['weight']
mainSim = Similarity
to_hash = '{} {}'.format(subject, object)
hashed_output = abs(hash(to_hash)) % (10 ** 8)
hashOut = hashed_output
writer.write('<{}> <{}{}> _:{} <{}> .'.format(sub1, relationToUse, relation, hashed_output, context))
writer.write('\n')
writer.write('<{}> <{}{}> _:{} <{}> .'.format(sub2, relationToUse, relation, hashed_output, context))
writer.write('\n')
writer.write('_:{} <{}Semantic_Similarity> "{}" <{}> .'.format(hashed_output, relationToUse, str(Similarity),context))
writer.write('\n')
# writer.write(get_continuous_chunks(my_sent))
except Exception as e:
pass
else:
# print("YAAAAAAAAAAAAAAAAAAs")
pass
def imageURLS(word, hashed_output, writer, relationToUse, context):
print("Inside the first functionnnns")
try:
myWord = wordnet.synsets(word)[0]
concept_offset = myWord.offset()
generated_id = len(str(concept_offset))
except Exception as e:
print(e)
else:
if generated_id != 8:
image_URL = "http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n0{}".format(concept_offset)
writer.write('_:{} <{}IURLs_{}> <{}> <{}> .'.format(hashed_output, relationToUse, word, image_URL, context))
writer.write('\n')
else:
image_URL = "http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n{}".format(concept_offset)
writer.write('_:{} <{}IURLs_{}> <{}> <{}> .'.format(hashed_output, relationToUse, word, image_URL, context))
writer.write('\n')
def specificImageURLs(word, hashed_output, writer, relationToUse, context):
print("Inside the secooond functionnnns")
try:
syns = wordnet.synsets('{}'.format(word))[0]
syn_offset = syns.offset()
page = requests.get('http://www.image-net.org/search?q={}'.format(word))
soup = BeautifulSoup(page.content, 'html.parser')
except Exception as e:
print(e)
else:
if len(str(syn_offset)) == 7:
try:
for link in soup.find_all('a', {'href': 'synset?wnid=n0{}'.format(syn_offset)}):
writer.write(
'_:{} <{}{}_Images> "http://www.image-net.org/{}" <{}> .'.format(hashed_output, relationToUse,
word, link.img['src'],
context))
writer.write('\n')
except Exception as e:
pass
else:
try:
for link in soup.find_all('a', {'href': 'synset?wnid=n{}'.format(syn_offset)}):
writer.write(
'_:{} <{}{}_Images> "http://www.image-net.org/{}" <{}> .'.format(hashed_output, relationToUse,
word, link.img['src'],
context))
writer.write('\n')
except Exception as e:
pass
def readFile(fileName, context):
start_time = time.time()
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
try:
reader = open(fileName, "r")
writer = open('output.nq', 'w+')
except Exception as e:
print(e)
else:
parity = itertools.cycle([True, False])
for line in reader:
line = line.replace('%20', ',').replace('%2C', ',')
if line.startswith("_:"):
writer.write('{} <{}> .'.format(line.strip().rstrip(' .'), context))
writer.write('\n')
continue
if line.isspace():
continue
if next(parity):
line1 = line
writer.write('{} <{}> .'.format(line1.strip().rstrip(' .'), context))
writer.write('\n')
line1 = re.findall('<([^>]*)>', line)
if len(line1) == 3:
sub_line1, rel_line1, obj_line1 = line1[0], line1[1], line1[2]
elif len(line1) == 2:
sub_line1, rel_line1 = line1[0], line1[1]
obj_line1 = re.findall('"([^"]*)"', line)[0]
else:
pass
finalSub = ''
sub1 = sub_line1
sub_line1 = sub_line1.split('/')[-1].upper()
try:
extractedSub = entityEtra.get_continuous_chunks(sub_line1.upper())
print("sub ext", extractedSub)
extractedSubLength = len(extractedSub)
except Exception as e:
print(e)
else:
# print("NLTK works perfectly")
if extractedSubLength == 0:
pass
elif extractedSubLength == 1:
finalSub = extractedSub[0]
else:
writer.write(
'<{}> <{}isA> <{}> <{}> .'.format(sub1, relationToUse,
'/'.join(sub1.split('/')[:-1]) + '/' + ','.join(
extractedSub),
context))
writer.write('\n')
# writer.write('{}'.format(extractedSub))
else:
line2 = line
writer.write('{} <{}> .'.format(line2.strip().rstrip(' .'), context))
writer.write('\n')
line2 = re.findall('<([^>]*)>', line)
if len(line2) == 3:
sub_line2, rel_line2, obj_line2 = line2[0], line2[1], line2[2]
elif len(line2) == 2:
sub_line2, rel_line2 = line2[0], line2[1]
obj_line2 = re.findall('"([^"]*)"', line)[0]
else:
pass
# writer.write("Both line: {}{}".format(line1, line2))
finalObj = ''
sub2 = sub_line2
sub_line2 = sub_line2.split('/')[-1].upper()
try:
extractedObj = entityEtra.get_continuous_chunks(sub_line2.upper())
print("obj ext", extractedObj)
extractedObjLength = len(extractedObj)
except Exception as e:
print(e)
else:
# print("NLTK works perfectly")
if extractedObjLength == 0:
pass
elif extractedObjLength == 1:
finalObj = extractedObj[0]
else:
writer.write('<{}> <{}isA> <{}> <{}> .'.format(sub2, relationToUse,
'/'.join(sub2.split('/')[:-1]) + '/' + ','.join(
extractedObj), context))
writer.write('\n')
sub_line1, sub_line2 = sub_line1.lower(), sub_line2.lower()
# Calculating the similarity between two normal words that have not been changed
finalSub, finalObj = finalSub.lower(), finalObj.lower()
extractedSub = [i.lower() for i in extractedSub]
extractedObj = [i.lower() for i in extractedObj]
if extractedSubLength == 0:
if extractedObjLength == 0:
calSimilarity(sub_line1, sub_line2, writer, sub1, sub2, context)
subToUse, objToUse = sub_line1, sub_line2
elif extractedObjLength == 1:
calSimilarity(sub_line1, finalObj, writer, sub1, sub2, context)
subToUse, objToUse = sub_line1, finalObj
else:
for everyObj in extractedObj:
calSimilarity(sub_line1, everyObj, writer, sub1, sub2, context)
subToUse, objToUse = sub_line1, everyObj
if mainSim != 0:
break
elif extractedSubLength == 1:
if extractedObjLength == 0:
calSimilarity(finalSub, sub_line2, writer, sub1, sub2, context)
subToUse, objToUse = finalSub, sub_line2
elif extractedObjLength == 1:
calSimilarity(finalSub, finalObj, writer, sub1, sub2, context)
subToUse, objToUse = finalSub, finalObj
else:
for everyObj1 in extractedObj:
calSimilarity(finalSub, everyObj1, writer, sub1, sub2, context)
subToUse, objToUse = finalSub, everyObj1
if mainSim != 0:
break
else:
if extractedObjLength == 0:
for everySub in extractedSub:
calSimilarity(everySub, sub_line2, writer, sub1, sub2, context)
subToUse, objToUse = everySub, sub_line2
if mainSim != 0:
break
elif extractedObjLength == 1:
for everySub1 in extractedSub:
calSimilarity(everySub1, finalObj, writer, sub1, sub2, context)
subToUse, objToUse = everySub1, finalObj
if mainSim != 0:
break
else:
for everySub2 in extractedSub:
for everyObj2 in extractedObj:
calSimilarity(everySub2, everyObj2, writer, sub1, sub2, context)
subToUse, objToUse = everySub2, everyObj2
if mainSim != 0:
break
print("sim is: ", mainSim)
if mainSim != 0:
print("Insssside the first if")
imageURLS(subToUse, hashOut, writer, relationToUse, context)
imageURLS(objToUse, hashOut, writer, relationToUse, context)
specificImageURLs(subToUse, hashOut, writer, relationToUse, context)
specificImageURLs(objToUse, hashOut, writer, relationToUse, context)
# print("DONNNNNNNNe ALL")
writer.flush()
writer.close()
readIn = open('output.nq')
data = readIn.read().replace('<', '<').replace('>', '>').replace('\n', '</br>')
readIn.close()
return data