-
Notifications
You must be signed in to change notification settings - Fork 3
/
get_resource.py
593 lines (463 loc) · 14.8 KB
/
get_resource.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
import re
# import CMUTweetTagger
#import cPickle
from collections import defaultdict
import pickle
from nltk.corpus import wordnet as wn
from itertools import product
import spacy
from spacy.symbols import *
from nltk import Tree
from nltk import *
import nltk
import location
import time
import sys
ps_stemmer=stem.porter.PorterStemmer()
nlp=spacy.load('en')
np_labels=set(['nsubj','dobj','pobj','iobj','conj','nsubjpass','appos','nmod','poss','parataxis','advmod','advcl'])
subj_labels=set(['nsubj','nsubjpass','csubj','csubjpass'])
modifiers=['nummod','compound','amod','punct']
after_clause_modifier=['relcl','acl','ccomp','xcomp','acomp','punct','advcl','rcmod']
tel_no="([+]?[0]?[1-9][0-9\s]*[-]?[0-9\s]+)"
email="([a-zA-Z0-9]?[a-zA-Z0-9_.]+[@][a-zA-Z]+[.](com|net|edu|in|org|en))"
web_url="http:[a-zA-Z._0-9/]+[a-zA-Z0-9]"
http_url='http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\)]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
entity_type_list=['NORP','ORG','GPE','PERSON']
quant_no="([0-9]*[,.]?[0-9]+[km]?)"
alphanum="[^0-9a-zA-Z ]"
stop_list=list(location.false_names)
#,'nn','quantmod','nmod','hmod','infmod']
need_file=open('DATA/Process_resources/need.txt')
offer_file=open('DATA/Process_resources/offer.txt')
shelter_file=open('DATA/Process_resources/shelter.txt')
food_file=open('DATA/Process_resources/food.txt')
medical_file=open('DATA/Process_resources/medical.txt')
cash_file=open('DATA/Process_resources/cash.txt')
logistics_file=open('DATA/Process_resources/logistics.txt')
disaster_events_file=open('DATA/Process_resources/disaster_events.txt')
basic_resource=['medical','water','sanitation','shelter','cloth','food','transport','infrastructure','volunteers','logistic']
need_verb_list=set()
for line in need_file:
line=line.rstrip().lower()
need_verb_list.add(line)
send_verb_list=set()
for line in offer_file:
line=line.rstrip().lower()
send_verb_list.add(line)
need_send_verb_list=list(need_verb_list)
need_send_verb_list.extend(list(send_verb_list))
common_resource=set()
dis_events=set()
for line in shelter_file:
line=line.rstrip().lower()
common_resource.add(line)
for line in cash_file:
line=line.rstrip().lower()
common_resource.add(line)
for line in food_file:
line=line.rstrip().lower()
common_resource.add(line)
for line in medical_file:
line=line.rstrip().lower()
common_resource.add(line)
for line in logistics_file:
line=line.rstrip().lower()
common_resource.add(line)
for line in disaster_events_file:
line=line.rstrip().lower()
dis_events.add(line)
dis_events_stem=[ps_stemmer.stem(i) for i in list(dis_events)]
common_resource=list(common_resource)
common_resource.extend([ps_stemmer.stem(i) for i in common_resource])
# try:
# input_name=sys.argv[1]
# except:
# input_name='nepal_needs'
# print(input_name)
# input_file='DATA/INPUT/'+input_name+'.txt'
# print(tweet_preprocess2(text,[]))
stop_list.extend(need_send_verb_list)
print("Loading done")
def get_contact(text):
contacts=[]
flag=0
numbers=re.findall(tel_no,text)
temp=set()
for i in numbers:
if len(i.replace(' ',''))>=7:
temp.add(i)
# print("Contact information:" +i)
contacts.append(temp)
temp=set()
mails= re.findall(email,text)
for i in mails:
temp.add(i)
# print("Mail: "+i[0])
contacts.append(temp)
temp=set()
urls= re.findall(http_url,text)
for i in urls:
temp.add(i)
# print("URL: "+i)
contacts.append(temp)
return contacts
# f=open(input_file,'r')
# print(contacts)
def modifier_word(word):
modified_word=word.orth_
while word.n_lefts+word.n_rights==1 and word.dep_.lower() in modifiers:
word=[child for child in word.children][0]
modified_word=word.orth_+" "+modified_word
return modified_word
def tok_format(tok):
return "_".join([tok.orth_, tok.dep_,tok.ent_type_])
def to_nltk_tree(node):
if node.n_lefts + node.n_rights > 0:
return Tree(tok_format(node), [to_nltk_tree(child) for child in node.children])
else:
return tok_format(node)
def get_verb_similarity_score(word,given_list,given_list_2):
max_verb_similarity=0
if word.lower() in given_list:
max_verb_similarity=1
else:
current_verb_list=wn.synsets(word.lower())
for verb in given_list_2:
related_verbs=wn.synsets(verb)
for a,b in product(related_verbs,current_verb_list):
d=wn.wup_similarity(a,b)
try:
if d> max_verb_similarity:
max_verb_similarity=d
except:
continue
return max_verb_similarity
def resource_in_list(resource):
related_resources=wn.synsets(resource)
max_similarity=0
chosen_word=""
if ps_stemmer.stem(resource.lower()) in common_resource:
return 1,resource
for word in basic_resource:
related_words=wn.synsets(word)
for a,b in product(related_words,related_resources):
d=wn.wup_similarity(a,b)
try:
if d> max_similarity:
max_similarity=d
chosen_word=word
except:
continue
return max_similarity, chosen_word
def get_children(word,resource_array,modified_array):
#print(word,word.dep_)
for child in word.children:
if child.dep_.lower() in modifiers:
get_word=modifier_word(child)+" "+word.orth_+"<_>"+word.dep_
modified_array.append(get_word)
if child.dep_.lower()=='prep' or child.dep_.lower()=='punct':
get_children(child,resource_array,modified_array)
if child.dep_.lower() in after_clause_modifier:
#print(child, child.dep_)
get_children(child,resource_array,modified_array)
if child.dep_.lower() in np_labels:
get_children(child,resource_array,modified_array)
resource_array.append(child.orth_+"<_>"+child.dep_)
else:
if get_verb_similarity_score(child.orth_,common_resource,basic_resource)>0.9:
get_children(child,resource_array,modified_array)
def get_resource(text):
doc=nlp(text)
# try:
# [to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]
# except:
# print("Exception here")
# print(time.time()-start_time,1)
org_list=[]
prev_word=""
prev_word_type=""
for word in doc:
if word.ent_type_ in entity_type_list:
org_list.append(word.orth_+"<_>"+word.ent_type_)
else:
org_list.append("<_>")
resource_array=[]
modified_array=[]
for word in doc:
if get_verb_similarity_score(word.orth_,need_send_verb_list,need_send_verb_list)>0.9 or word.dep_=='ROOT':
get_children(word,resource_array,modified_array)
if word.dep_=='cc' and word.n_lefts+word.n_rights==0:
ancestor=word.head.orth_
#print(ancestor)
if get_verb_similarity_score(ancestor,common_resource,basic_resource)>0.9:
get_children(word.head,resource_array,modified_array)
last_word=[]
final_resource={}
modified_array_2=[]
resource_array_2=[]
n_subj_list=[]
# print(time.time()-start_time,2)
# print("Modified array", modified_array)
# print("Resource array", resource_array)
for i in modified_array:
modified_array_2.append(i[:(i.index("<_>"))])
for i in resource_array:
resource_array_2.append(i[:(i.index("<_>"))])
modified_array_2=[re.sub(alphanum,"",i.strip()) for i in modified_array_2]
modified_array_2=list(set([i.strip() for i in modified_array_2]))
resource_array_2=[re.sub(alphanum,"",i.strip()) for i in resource_array_2]
resource_array_2=list(set([i.strip() for i in resource_array_2]))
# print("Resource array: ",resource_array_2)
# print("Modified array: ", modified_array_2)
for resources in modified_array_2:
max_val_resource=-1
val_type=""
resource_list=resources.strip().split(" ")
for resource in resource_list:
pres_res_val,pres_res_type=resource_in_list(resource)
# print(resource,pres_res_val,pres_res_type)
if max_val_resource==-1:
max_val_resource=pres_res_val
if pres_res_val> max_val_resource:
val_type=pres_res_type
max_val_resource=pres_res_val
if pres_res_val> 0.8:
final_resource[resource]=pres_res_type
if max_val_resource > 0.9:
final_resource[resources]=val_type
# print(time.time()-start_time,3)
for resource in resource_array_2:
#print(resource)
pres_res_val,pres_res_type=resource_in_list(resource)
if pres_res_val> 0.8:
if resource not in final_resource:
final_resource[resource]=pres_res_type
final_resource_keys=list(final_resource.keys())
prev_word_type=""
prev_word=""
org_list_2=[]
for i in org_list:
index=i.index("<_>")
if i[index+3:]=="ORG" and prev_word_type=="ORG":
prev_word=prev_word+" "+i[:index]
elif i[index+3:]=="PERSON" and prev_word_type=="PERSON":
prev_word=prev_word+" "+i[:index]
else:
if prev_word !='':
org_list_2.append(prev_word+"<_>"+prev_word_type)
prev_word_type=i[index+3:]
prev_word=i[:index]
source_list=[]
org_person_list=[]
for i in org_list_2:
tag=i[i.index("<_>")+3:]
j=i[:i.index("<_>")]
if tag=="ORG" or tag=="PERSON" or tag=='GPE' or tag=='LOC':
if j.lower() not in stop_list:
org_person_list.append(j)
elif j.lower() not in stop_list :
source_list.append(j)
else:
continue
for i in modified_array:
pos_res=i[:i.index("<_>")]
pos_tag=i[i.index("<_>")+3:]
if pos_tag in subj_labels:
if pos_res not in source_list and pos_res not in final_resource_keys and pos_res.lower() not in stop_list:
#print(pos_tag,pos_res)
source_list.append(pos_res)
for i in resource_array:
pos_res=i[:i.index("<_>")]
pos_tag=i[i.index("<_>")+3:]
if pos_tag in subj_labels:
if pos_res not in source_list and pos_res not in final_resource_keys and pos_res.lower() not in stop_list:
#print(pos_tag,pos_res)
source_list.append(pos_res)
pos_tags_dict={}
doc2=nlp(text.lower())
for word in doc2:
try:
pos_tags_dict[word.orth_]=word.pos_
except:
continue
final_resource_keys_2=[]
for elem in final_resource_keys:
elem2=elem.split()
poss=[]
for i in elem2:
try:
poss.append(pos_tags_dict[i.lower()])
except Exception as e:
continue
# poss=[pos_tags_dict[i.lower()] for i in elem2]
if poss==[]:
continue
if 'VERB' not in poss and( poss[-1]=='NOUN'):
final_resource_keys_2.append(elem)
return final_resource_keys_2,source_list,org_person_list,modified_array
def jumble(text,items):
final_items=[]
for item in items:
if item in text:
final_items.append(item)
temp_list=[]
for item1 in final_items:
for item2 in final_items:
if item1+' '+item2 in text:
temp_list.append(item1+' '+item2)
final_items.extend(temp_list)
items=list(set(items)-set(final_items))
while True:
add_list=[]
rem_list=[]
item_list=[]
for item in items:
item_split=item.split()
for elem in final_items:
for k in item_split:
if k+' '+elem in text:
add_list.append(k+' '+elem)
rem_list.append(elem)
item_list.append(item)
if elem+' '+k in text:
add_list.append(elem+' '+k)
rem_list.append(elem)
item_list.append(item)
if add_list==[]:
break
else:
final_items.extend(add_list)
items= list(set(items)-set(item_list))
return final_items
def post_process(text,final_resource_keys,source_list,loc_list):
source_dis=set()
resource_dis=set()
for loc in loc_list:
for elem in source_list:
elem2=elem
elem=elem.lower()
if loc in elem or elem in loc or elem in stop_list:
source_dis.add(elem2)
continue
for elem in final_resource_keys:
elem2=elem
elem=elem.lower()
if loc in elem or elem in loc or elem in stop_list:
resource_dis.add(elem2)
continue
source_list=list(set(source_list)- source_dis)
final_resource_keys=list(set(final_resource_keys)- resource_dis)
source_list_2=[]
source_dis=set()
for elem in source_list:
elem_split=[ps_stemmer.stem(i) for i in elem.lower().split()]
flag=False
for i in elem_split:
if i in dis_events_stem:
flag=True
break
if flag==True:
source_dis.add(elem)
continue
for elem2 in source_list:
if elem2 ==elem:
continue
if elem2 in source_dis:
continue
if elem2 in elem :
source_dis.add(elem2)
if elem in elem2:
source_dis.add(elem)
source_list=list(set(source_list)- source_dis)
source_list=jumble(text,source_list)
dup_final_resource_keys=list(final_resource_keys)
final_resource_keys=jumble(text,final_resource_keys)
source_dis=set()
resource_dis=set()
for elem in source_list:
for elem2 in source_list:
if elem2 ==elem:
continue
if elem2 in source_dis:
continue
if elem2 in elem :
source_dis.add(elem2)
if elem in elem2:
source_dis.add(elem)
for elem3 in final_resource_keys:
if elem in elem3 or elem3 in elem:
source_dis.add(elem)
for elem in final_resource_keys:
for elem2 in final_resource_keys:
if elem2 ==elem:
continue
if elem2 in resource_dis:
continue
if elem2 in elem :
resource_dis.add(elem2)
if elem in elem2:
resource_dis.add(elem)
source_list=list(set(source_list)- source_dis)
final_resource_keys=list(set(final_resource_keys)- resource_dis)
return source_list,final_resource_keys,loc_list ,dup_final_resource_keys
# print(source_list)
# print(final_resource_keys)
# print(loc_list)
def create_resource_list(text):
count=0
quantity_dict={}
final_resource_keys=[]
source_list=[]
loc_list=[]
org_person_list=[]
loc_list_2=location.return_location_list(text)
final_resource_keys,source_list,org_person_list,modified_array= get_resource(text)
doc=nlp(text)
for elem in source_list:
if elem.lower() in location.curr_loc_dict and elem.lower() not in stop_list:
loc_list_2.append((elem.lower(),location.curr_loc_dict[elem.lower()]))
for elem in org_person_list:
if elem.lower() in location.curr_loc_dict and elem.lower() not in stop_list:
loc_list_2.append((elem.lower(),location.curr_loc_dict[elem.lower()]))
loc_list=list(set([i[0] for i in loc_list_2]))
source_list= [i for i in source_list if i.lower() not in loc_list]
org_person_list=[i for i in org_person_list if i.lower() not in loc_list]
source_list=list(set(source_list) | set(org_person_list))
final_resource_keys=[i for i in final_resource_keys if i.lower() not in loc_list]
# print(text)
a,b,c,d=post_process(text, final_resource_keys,source_list,loc_list)
# print(a)
# print(b)
# print(c)
return a,b,loc_list_2,modified_array,d
global_resource_list={}
def show_resource(text):
contacts=get_contact(text)
text=location.tweet_preprocess2(text,[])
a,b,c,modified_array,d=create_resource_list(text)
'''
a= source list
b= final resource keys
c= loc_list
d= dup_final_resource keys
'''
print("Phone number ", contacts[0])
print("Email ", contacts[1])
print("List of sources ", a)
print("Resource list ", b)
print("List of possible locations ", set(c))
# print(d)
sample_text='We need food in Nepal'
show_resource(sample_text)
# for line in f:
# start_time=time.time()
# line=line.rstrip().split('<||>')
# tid=line[0]
# text=line[1]
# contacts=get_contact(text)
# text=location.tweet_preprocess2(text,[])
# a,b,c,modified_array,d=create_resource_list(text)
# global_resource_list[tid]=((text,a,b,c,contacts,modified_array,d))
# with open('DATA/OUTPUT/'+input_name+'.p','wb')as handle:
# pickle.dump(global_resource_list,handle)