-
Notifications
You must be signed in to change notification settings - Fork 0
/
aligner.py
1047 lines (812 loc) · 52.5 KB
/
aligner.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
from alignerConfig import AlignerConfig
from wordSim import *
from util import *
from coreNlpUtil import *
from operator import itemgetter
class Aligner(object):
config = None
def __init__(self, language):
self.config = AlignerConfig(language)
def is_similar(self, item1, item2, pos1, pos2, is_opposite, relation):
result = False
group = self.config.get_similar_group(pos1, pos2, is_opposite, relation)
if is_opposite:
for subgroup in group:
if item1 in subgroup[0] and item2 in subgroup[1]:
result = True
else:
for subgroup in group:
if item1 in subgroup and item2 in subgroup:
result = True
return result
def compareNodes(self, sourceNodes, targetNodes, pos, opposite, relationDirection, existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas):
# search for nodes in common or equivalent function
relativeAlignments = []
wordSimilarities = []
for ktem in sourceNodes:
for ltem in targetNodes:
word1 = Word(ktem[0], ktem[1], sourceLemmas[ktem[0]-1], sourcePosTags[ktem[0]-1], ktem[2])
word2 = Word(ltem[0], ltem[1], targetLemmas[ltem[0]-1], targetPosTags[ltem[0]-1], ltem[2])
if ([ktem[0], ltem[0]] in existingAlignments or wordRelatednessAlignment(word1, word2, self.config) >= self.config.alignment_similarity_threshold) and (
#(ktem[2] == ltem[2])):
(ktem[2] == ltem[2]) or
((pos != '' and relationDirection != 'child_parent') and (
self.is_similar(ktem[2], ltem[2], pos, 'noun', opposite, relationDirection) or
self.is_similar(ktem[2], ltem[2], pos, 'verb', opposite, relationDirection) or
self.is_similar(ktem[2], ltem[2], pos, 'adjective', opposite, relationDirection) or
self.is_similar(ktem[2], ltem[2], pos, 'adverb', opposite, relationDirection))) or
((pos != '' and relationDirection == 'child_parent') and (
self.is_similar(ltem[2], ktem[2], pos, 'noun', opposite, relationDirection) or
self.is_similar(ltem[2], ktem[2], pos, 'verb', opposite, relationDirection) or
self.is_similar(ltem[2], ktem[2], pos, 'adjective', opposite, relationDirection) or
self.is_similar(ltem[2], ktem[2], pos, 'adverb', opposite, relationDirection)))):
relativeAlignments.append([ktem[0], ltem[0]])
wordSimilarities.append(wordRelatednessAlignment(word1, word2, self.config))
alignmentResults = {}
for i, alignment in enumerate(relativeAlignments):
alignmentResults[(alignment[0], alignment[1])] = wordSimilarities[i]
return alignmentResults
def compareNodesScoring(self, sourceNodes, targetNodes, pos, opposite, relationDirection, existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas):
# search for nodes in common or equivalent function
relativeAlignments = []
wordSimilarities = []
for ktem in sourceNodes:
for ltem in targetNodes:
word1 = Word(ktem[0], ktem[1], sourceLemmas[ktem[0]-1], sourcePosTags[ktem[0]-1], ktem[2])
word2 = Word(ltem[0], ltem[1], targetLemmas[ltem[0]-1], targetPosTags[ltem[0]-1], ltem[2])
if ([ktem[0], ltem[0]] in existingAlignments or (ktem[0] == 0 and ltem[0] == 0)) and (
#(ktem[2] == ltem[2])):
(ktem[2] == ltem[2]) or
((pos != '' and relationDirection != 'child_parent') and (
self.is_similar(ktem[2], ltem[2], pos, 'noun', opposite, relationDirection) or
self.is_similar(ktem[2], ltem[2], pos, 'verb', opposite, relationDirection) or
self.is_similar(ktem[2], ltem[2], pos, 'adjective', opposite, relationDirection) or
self.is_similar(ktem[2], ltem[2], pos, 'adverb', opposite, relationDirection))) or
((pos != '' and relationDirection == 'child_parent') and (
self.is_similar(ltem[2], ktem[2], pos, 'noun', opposite, relationDirection) or
self.is_similar(ltem[2], ktem[2], pos, 'verb', opposite, relationDirection) or
self.is_similar(ltem[2], ktem[2], pos, 'adjective', opposite, relationDirection) or
self.is_similar(ltem[2], ktem[2], pos, 'adverb', opposite, relationDirection)))):
relativeAlignments.append([ktem[0], ltem[0]])
wordSimilarities.append(wordRelatednessAlignment(word1, word2, self.config))
alignmentResults = {}
for i, alignment in enumerate(relativeAlignments):
alignmentResults[(alignment[0], alignment[1])] = wordSimilarities[i]
return alignmentResults
def calculateAbsoluteScore(self, wordSimilarities):
maxLeft = {}
maxRight = {}
maxLeftList = {}
maxRightList = {}
for similarity in wordSimilarities.keys():
if not maxLeft.has_key(similarity[0]) or wordSimilarities[maxLeft[similarity[0]]] < wordSimilarities[similarity]:
maxLeft[similarity[0]] = similarity
maxLeftList[similarity[0]] = similarity[1]
if not maxRight.has_key(similarity[1]) or wordSimilarities[maxRight[similarity[1]]] < wordSimilarities[similarity]:
maxRight[similarity[1]] = similarity
maxRightList[similarity[1]] = similarity[0]
maxRelations = set(maxLeft.values() + maxRight.values())
score = 0
sourceNodesConsidered = []
targetNodesConsidered = []
for rel in maxRelations:
if rel[0] not in sourceNodesConsidered and rel[1] not in targetNodesConsidered:
score += wordSimilarities[rel]
sourceNodesConsidered.append(rel[0])
targetNodesConsidered.append(rel[1])
return score
def findDependencySimilarity(self, pos, source, sourceIndex, target, targetIndex, sourceDParse, targetDParse, existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas):
sourceWordParents = findParents(sourceDParse, sourceIndex, source)
sourceWordChildren = findChildren(sourceDParse, sourceIndex, source)
targetWordParents = findParents(targetDParse, targetIndex, target)
targetWordChildren = findChildren(targetDParse, targetIndex, target)
compareParents = self.compareNodes(sourceWordParents, targetWordParents, pos, False, 'parent', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
compareChildren = self.compareNodes(sourceWordChildren, targetWordChildren, pos, False, 'child', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
compareParentChildren = self.compareNodes(sourceWordParents, targetWordChildren, pos, True, 'parent_child', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
compareChildrenParent = self.compareNodes(sourceWordParents, targetWordChildren, pos, True, 'child_parent', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
comparisonResult = dict(compareParents.items() + compareChildren.items() + compareChildrenParent.items() + compareParentChildren.items())
alignments = []
wordSimilarities = {}
for alignment in comparisonResult.keys():
alignments.append([alignment[0], alignment[1]])
wordSimilarities[alignment] = comparisonResult[alignment]
return [self.calculateAbsoluteScore(wordSimilarities),
alignments]
def findDependencyDifference(self, pos, source, sourceIndex, target, targetIndex, sourceDParse, targetDParse, existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas):
sourceWordParents = findParents(sourceDParse, sourceIndex, source)
sourceWordChildren = findChildren(sourceDParse, sourceIndex, source)
targetWordParents = findParents(targetDParse, targetIndex, target)
targetWordChildren = findChildren(targetDParse, targetIndex, target)
compareParents = self.compareNodesScoring(sourceWordParents, targetWordParents, pos, False, 'parent', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
compareChildren = self.compareNodesScoring(sourceWordChildren, targetWordChildren, pos, False, 'child', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
compareParentChildren = self.compareNodesScoring(sourceWordParents, targetWordChildren, pos, True, 'parent_child', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
compareChildrenParent = self.compareNodesScoring(sourceWordParents, targetWordChildren, pos, True, 'child_parent', existingAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
labelsSource = []
labelsTarget = []
childrenMatchedSource = []
parentsMatchedSource = []
childrenMatchedTarget = []
parentsMatchedTarget = []
for item in compareChildren.keys():
childrenMatchedTarget.append(item[1])
childrenMatchedSource.append(item[0])
for item in compareParents.keys():
parentsMatchedTarget.append(item[1])
parentsMatchedSource.append(item[0])
for item in compareChildrenParent.keys():
childrenMatchedTarget.append(item[1])
parentsMatchedTarget.append(item[1])
childrenMatchedSource.append(item[0])
parentsMatchedSource.append(item[0])
for item in compareParentChildren.keys():
childrenMatchedTarget.append(item[1])
parentsMatchedTarget.append(item[1])
childrenMatchedSource.append(item[0])
parentsMatchedSource.append(item[0])
for item in targetWordChildren:
if item[0] not in childrenMatchedTarget:
labelsTarget.append(item[2])
for item in targetWordParents:
if item[0] not in parentsMatchedTarget:
labelsTarget.append(item[2])
for item in sourceWordChildren:
if item[0] not in childrenMatchedSource:
labelsSource.append(item[2])
for item in sourceWordParents:
if item[0] not in parentsMatchedSource:
labelsSource.append(item[2])
return [labelsSource, labelsTarget]
##############################################################################################################################
def alignPos(self, pos, posCode, source, target, sourceParseResult, targetParseResult, existingAlignments):
# source and target:: each is a list of elements of the form:
# [[character begin offset, character end offset], word index, word, lemma, pos tag]
global scorer
posAlignments = []
sourceWordIndices = [i+1 for i in xrange(len(source))]
targetWordIndices = [i+1 for i in xrange(len(target))]
sourceWordIndicesAlreadyAligned = sorted(list(set([item[0] for item in existingAlignments])))
targetWordIndicesAlreadyAligned = sorted(list(set([item[1] for item in existingAlignments])))
sourceWords = [item[2] for item in source]
targetWords = [item[2] for item in target]
sourceLemmas = [item[3] for item in source]
targetLemmas = [item[3] for item in target]
sourcePosTags = [item[4] for item in source]
targetPosTags = [item[4] for item in target]
sourceDParse = dependencyParseAndPutOffsets(sourceParseResult)
targetDParse = dependencyParseAndPutOffsets(targetParseResult)
numberOfPosWordsInSource = 0
evidenceCountsMatrix = {}
relativeAlignmentsMatrix = {}
wordSimilarities = {}
# construct the two matrices in the following loop
for i in sourceWordIndices:
if i in sourceWordIndicesAlreadyAligned or (sourcePosTags[i-1][0].lower() != posCode and sourcePosTags[i-1].lower() != 'prp'):
continue
numberOfPosWordsInSource += 1
for j in targetWordIndices:
if j in targetWordIndicesAlreadyAligned or (targetPosTags[j-1][0].lower() != posCode and targetPosTags[j-1].lower() != 'prp'):
continue
word1 = Word(i, sourceWords[i-1], sourceLemmas[i-1], sourcePosTags[i-1], '')
word2 = Word(j, targetWords[j-1], targetLemmas[j-1], targetPosTags[j-1], '')
if wordRelatednessAlignment(word1, word2, self.config) < self.config.alignment_similarity_threshold:
continue
wordSimilarities[(i, j)] = wordRelatednessAlignment(word1, word2, self.config)
dependencySimilarity = self.findDependencySimilarity(pos, source, i, target, j, sourceDParse, targetDParse, existingAlignments + posAlignments, sourcePosTags, targetPosTags, sourceLemmas, targetLemmas)
if wordSimilarities[(i, j)] == self.config.alignment_similarity_threshold:
if wordSimilarities[(i, j)] + dependencySimilarity[0] <= 1.0:
continue
if dependencySimilarity[0] >= self.config.alignment_similarity_threshold:
evidenceCountsMatrix[(i, j)] = dependencySimilarity[0]
relativeAlignmentsMatrix[(i, j)] = dependencySimilarity[1]
else:
evidenceCountsMatrix[(i, j)] = 0
# now use the collected stats to align
for n in xrange(numberOfPosWordsInSource):
maxEvidenceCountForCurrentPass = 0
maxOverallValueForCurrentPass = 0
indexPairWithStrongestTieForCurrentPass = [-1, -1]
for i in sourceWordIndices:
if i in sourceWordIndicesAlreadyAligned or sourcePosTags[i-1][0].lower() != posCode or sourceLemmas[i-1].lower() in stopwords:
continue
for j in targetWordIndices:
if j in targetWordIndicesAlreadyAligned or targetPosTags[j-1][0].lower() != posCode or targetLemmas[j-1].lower() in stopwords:
continue
if (i, j) in evidenceCountsMatrix and self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * evidenceCountsMatrix[(i, j)] > maxOverallValueForCurrentPass:
maxOverallValueForCurrentPass = self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * evidenceCountsMatrix[(i, j)]
maxEvidenceCountForCurrentPass = evidenceCountsMatrix[(i, j)]
indexPairWithStrongestTieForCurrentPass = [i, j]
#if maxEvidenceCountForCurrentPass > 0:
if maxOverallValueForCurrentPass > 0:
posAlignments.append(indexPairWithStrongestTieForCurrentPass)
sourceWordIndicesAlreadyAligned.append(indexPairWithStrongestTieForCurrentPass[0])
targetWordIndicesAlreadyAligned.append(indexPairWithStrongestTieForCurrentPass[1])
else:
break
return posAlignments
##############################################################################################################################
def alignNamedEntities(self, source, target, sourceParseResult, targetParseResult, existingAlignments):
# source and target:: each is a list of elements of the form:
# [[character begin offset, character end offset], word index, word, lemma, pos tag]
global punctuations
alignments = []
sourceNamedEntities = ner(sourceParseResult)
sourceNamedEntities = sorted(sourceNamedEntities, key=len)
targetNamedEntities = ner(targetParseResult)
targetNamedEntities = sorted(targetNamedEntities, key=len)
# learn from the other sentence that a certain word/phrase is a named entity (learn for source from target)
for item in source:
alreadyIncluded = False
for jtem in sourceNamedEntities:
if item[1] in jtem[1]:
alreadyIncluded = True
break
if alreadyIncluded or (len(item[2]) > 0 and not item[2][0].isupper()):
continue
for jtem in targetNamedEntities:
if item[2] in jtem[2]:
# construct the item
newItem = [[item[0]], [item[1]], [item[2]], jtem[3]]
# check if the current item is part of a named entity part of which has already been added (by checking contiguousness)
partOfABiggerName = False
for k in xrange(len(sourceNamedEntities)):
if sourceNamedEntities[k][1][len(sourceNamedEntities[k][1])-1] == newItem[1][0] - 1:
sourceNamedEntities[k][0].append(newItem[0][0])
sourceNamedEntities[k][1].append(newItem[1][0])
sourceNamedEntities[k][2].append(newItem[2][0])
partOfABiggerName = True
if not partOfABiggerName:
sourceNamedEntities.append(newItem)
elif isAcronym(item[2], jtem[2]) and [[item[0]], [item[1]], [item[2]], jtem[3]] not in sourceNamedEntities:
sourceNamedEntities.append([[item[0]], [item[1]], [item[2]], jtem[3]])
# learn from the other sentence that a certain word/phrase is a named entity (learn for target from source)
for item in target:
alreadyIncluded = False
for jtem in targetNamedEntities:
if item[1] in jtem[1]:
alreadyIncluded = True
break
if alreadyIncluded or (len(item[2]) > 0 and not item[2][0].isupper()):
continue
for jtem in sourceNamedEntities:
if item[2] in jtem[2]:
# construct the item
newItem = [[item[0]], [item[1]], [item[2]], jtem[3]]
# check if the current item is part of a named entity part of which has already been added (by checking contiguousness)
partOfABiggerName = False
for k in xrange(len(targetNamedEntities)):
if targetNamedEntities[k][1][len(targetNamedEntities[k][1])-1] == newItem[1][0] - 1:
targetNamedEntities[k][0].append(newItem[0][0])
targetNamedEntities[k][1].append(newItem[1][0])
targetNamedEntities[k][2].append(newItem[2][0])
partOfABiggerName = True
if not partOfABiggerName:
targetNamedEntities.append(newItem)
elif isAcronym(item[2], jtem[2]) and [[item[0]], [item[1]], [item[2]], jtem[3]] not in targetNamedEntities:
targetNamedEntities.append([[item[0]], [item[1]], [item[2]], jtem[3]])
sourceWords = []
targetWords = []
for item in sourceNamedEntities:
for jtem in item[1]:
if item[3] in ['PERSON', 'ORGANIZATION', 'LOCATION']:
sourceWords.append(source[jtem-1][2])
for item in targetNamedEntities:
for jtem in item[1]:
if item[3] in ['PERSON', 'ORGANIZATION', 'LOCATION']:
targetWords.append(target[jtem-1][2])
if len(sourceNamedEntities) == 0 or len(targetNamedEntities) == 0:
return []
sourceNamedEntitiesAlreadyAligned = []
targetNamedEntitiesAlreadyAligned = []
# align all full matches
for item in sourceNamedEntities:
if item[3] not in ['PERSON', 'ORGANIZATION', 'LOCATION']:
continue
# do not align if the current source entity is present more than once
count = 0
for ktem in sourceNamedEntities:
if ktem[2] == item[2]:
count += 1
if count > 1:
continue
for jtem in targetNamedEntities:
if jtem[3] not in ['PERSON', 'ORGANIZATION', 'LOCATION']:
continue
# do not align if the current target entity is present more than once
count = 0
for ktem in targetNamedEntities:
if ktem[2] == jtem[2]:
count += 1
if count > 1:
continue
# get rid of dots and hyphens
canonicalItemWord = [i.replace('.', '') for i in item[2]]
canonicalItemWord = [i.replace('-', '') for i in item[2]]
canonicalJtemWord = [j.replace('.', '') for j in jtem[2]]
canonicalJtemWord = [j.replace('-', '') for j in jtem[2]]
if canonicalItemWord == canonicalJtemWord:
for k in xrange(len(item[1])):
if ([item[1][k], jtem[1][k]]) not in alignments:
alignments.append([item[1][k], jtem[1][k]])
sourceNamedEntitiesAlreadyAligned.append(item)
targetNamedEntitiesAlreadyAligned.append(jtem)
# align acronyms with their elaborations
for item in sourceNamedEntities:
if item[3] not in ['PERSON', 'ORGANIZATION', 'LOCATION']:
continue
for jtem in targetNamedEntities:
if jtem[3] not in ['PERSON', 'ORGANIZATION', 'LOCATION']:
continue
if len(item[2])==1 and isAcronym(item[2][0], jtem[2]):
for i in xrange(len(jtem[1])):
if [item[1][0], jtem[1][i]] not in alignments:
alignments.append([item[1][0], jtem[1][i]])
sourceNamedEntitiesAlreadyAligned.append(item[1][0])
targetNamedEntitiesAlreadyAligned.append(jtem[1][i])
elif len(jtem[2])==1 and isAcronym(jtem[2][0], item[2]):
for i in xrange(len(item[1])):
if [item[1][i], jtem[1][0]] not in alignments:
alignments.append([item[1][i], jtem[1][0]])
sourceNamedEntitiesAlreadyAligned.append(item[1][i])
targetNamedEntitiesAlreadyAligned.append(jtem[1][0])
# align subset matches
for item in sourceNamedEntities:
if item[3] not in ['PERSON', 'ORGANIZATION', 'LOCATION'] or item in sourceNamedEntitiesAlreadyAligned:
continue
# do not align if the current source entity is present more than once
count = 0
for ktem in sourceNamedEntities:
if ktem[2] == item[2]:
count += 1
if count > 1:
continue
for jtem in targetNamedEntities:
if jtem[3] not in ['PERSON', 'ORGANIZATION', 'LOCATION'] or jtem in targetNamedEntitiesAlreadyAligned:
continue
if item[3] != jtem[3]:
continue
# do not align if the current target entity is present more than once
count = 0
for ktem in targetNamedEntities:
if ktem[2] == jtem[2]:
count += 1
if count > 1:
continue
# find if the first is a part of the second
if isSublist(item[2], jtem[2]):
unalignedWordIndicesInTheLongerName = []
for ktem in jtem[1]:
unalignedWordIndicesInTheLongerName.append(ktem)
for k in xrange(len(item[2])):
for l in xrange(len(jtem[2])):
if item[2][k] == jtem[2][l] and [item[1][k], jtem[1][l]] not in alignments:
alignments.append([item[1][k], jtem[1][l]])
if jtem[1][l] in unalignedWordIndicesInTheLongerName:
unalignedWordIndicesInTheLongerName.remove(jtem[1][l])
for k in xrange(len(item[1])): # the shorter name
for l in xrange(len(jtem[1])): # the longer name
# find if the current term in the longer name has already been aligned (before calling alignNamedEntities()), do not align it in that case
alreadyInserted = False
for mtem in existingAlignments:
if mtem[1] == jtem[1][l]:
alreadyInserted = True
break
if jtem[1][l] not in unalignedWordIndicesInTheLongerName or alreadyInserted:
continue
if [item[1][k], jtem[1][l]] not in alignments and target[jtem[1][l]-1][2] not in sourceWords and item[2][k] not in punctuations and jtem[2][l] not in punctuations:
alignments.append([item[1][k], jtem[1][l]])
# else find if the second is a part of the first
elif isSublist(jtem[2], item[2]):
unalignedWordIndicesInTheLongerName = []
for ktem in item[1]:
unalignedWordIndicesInTheLongerName.append(ktem)
for k in xrange(len(jtem[2])):
for l in xrange(len(item[2])):
if jtem[2][k] == item[2][l] and [item[1][l], jtem[1][k]] not in alignments:
alignments.append([item[1][l], jtem[1][k]])
if item[1][l] in unalignedWordIndicesInTheLongerName:
unalignedWordIndicesInTheLongerName.remove(item[1][l])
for k in xrange(len(jtem[1])): # the shorter name
for l in xrange(len(item[1])): # the longer name
# find if the current term in the longer name has already been aligned (before calling alignNamedEntities()), do not align it in that case
alreadyInserted = False
for mtem in existingAlignments:
if mtem[0] == item[1][k]:
alreadyInserted = True
break
if item[1][l] not in unalignedWordIndicesInTheLongerName or alreadyInserted:
continue
if [item[1][l], jtem[1][k]] not in alignments and source[item[1][k]-1][2] not in targetWords and item[2][l] not in punctuations and jtem[2][k] not in punctuations:
alignments.append([item[1][l], jtem[1][k]])
return alignments
def alignWords(self, source, target, sourceParseResult, targetParseResult):
# source and target:: each is a list of elements of the form:
# [[character begin offset, character end offset], word index, word, lemma, pos tag]
# function returns the word alignments from source to target - each alignment returned is of the following form:
# [
# [[source word character begin offset, source word character end offset], source word index, source word, source word lemma],
# [[target word character begin offset, target word character end offset], target word index, target word, target word lemma]
# ]
global punctuations
sourceWordIndices = [i+1 for i in xrange(len(source))]
targetWordIndices = [i+1 for i in xrange(len(target))]
alignments = []
sourceWordIndicesAlreadyAligned = []
targetWordIndicesAlreadyAligned = []
sourceWords = [item[2] for item in source]
targetWords = [item[2] for item in target]
sourceLemmas = [item[3] for item in source]
targetLemmas = [item[3] for item in target]
sourcePosTags = [item[4] for item in source]
targetPosTags = [item[4] for item in target]
# align the sentence ending punctuation first
if (sourceWords[len(source)-1] in ['.', '!'] and targetWords[len(target)-1] in ['.', '!']) or sourceWords[len(source)-1] == targetWords[len(target)-1]:
alignments.append([len(source), len(target)])
sourceWordIndicesAlreadyAligned.append(len(source))
targetWordIndicesAlreadyAligned.append(len(target))
elif sourceWords[len(source)-2] in ['.', '!'] and targetWords[len(target)-1] in ['.', '!']:
alignments.append([len(source)-1, len(target)])
sourceWordIndicesAlreadyAligned.append(len(source)-1)
targetWordIndicesAlreadyAligned.append(len(target))
elif sourceWords[len(source)-1] in ['.', '!'] and targetWords[len(target)-2] in ['.', '!']:
alignments.append([len(source), len(target)-1])
sourceWordIndicesAlreadyAligned.append(len(source))
targetWordIndicesAlreadyAligned.append(len(target)-1)
elif sourceWords[len(source)-2] in ['.', '!'] and targetWords[len(target)-2] in ['.', '!']:
alignments.append([len(source)-1, len(target)-1])
sourceWordIndicesAlreadyAligned.append(len(source)-1)
targetWordIndicesAlreadyAligned.append(len(target)-1)
# align all (>=2)-gram matches with at least one content word
commonContiguousSublists = findAllCommonContiguousSublists(sourceWords, targetWords, True)
for item in commonContiguousSublists:
allStopWords = True
for jtem in item:
if jtem not in stopwords and jtem not in punctuations:
allStopWords = False
break
if len(item[0]) >= 2 and not allStopWords:
for j in xrange(len(item[0])):
if item[0][j]+1 not in sourceWordIndicesAlreadyAligned and item[1][j]+1 not in targetWordIndicesAlreadyAligned and [item[0][j]+1, item[1][j]+1] not in alignments:
alignments.append([item[0][j]+1, item[1][j]+1])
sourceWordIndicesAlreadyAligned.append(item[0][j]+1)
targetWordIndicesAlreadyAligned.append(item[1][j]+1)
# align hyphenated word groups
for i in sourceWordIndices:
if i in sourceWordIndicesAlreadyAligned:
continue
if '-' in sourceWords[i-1] and sourceWords[i-1] != '-':
tokens = sourceWords[i-1].split('-')
commonContiguousSublists = findAllCommonContiguousSublists(tokens, targetWords)
for item in commonContiguousSublists:
if len(item[0]) > 1:
for jtem in item[1]:
if [i, jtem+1] not in alignments:
alignments.append([i, jtem+1])
sourceWordIndicesAlreadyAligned.append(i)
targetWordIndicesAlreadyAligned.append(jtem+1)
for i in targetWordIndices:
if i in targetWordIndicesAlreadyAligned:
continue
if '-' in target[i-1][2] and target[i-1][2] != '-':
tokens = target[i-1][2].split('-')
commonContiguousSublists = findAllCommonContiguousSublists(sourceWords, tokens)
for item in commonContiguousSublists:
if len(item[0]) > 1:
for jtem in item[0]:
if [jtem+1, i] not in alignments:
alignments.append([jtem+1, i])
sourceWordIndicesAlreadyAligned.append(jtem+1)
targetWordIndicesAlreadyAligned.append(i)
# align named entities
neAlignments = self.alignNamedEntities(source, target, sourceParseResult, targetParseResult, alignments)
for item in neAlignments:
if item not in alignments:
alignments.append(item)
if item[0] not in sourceWordIndicesAlreadyAligned:
sourceWordIndicesAlreadyAligned.append(item[0])
if item[1] not in targetWordIndicesAlreadyAligned:
targetWordIndicesAlreadyAligned.append(item[1])
# align words based on word and dependency match
sourceDParse = dependencyParseAndPutOffsets(sourceParseResult)
targetDParse = dependencyParseAndPutOffsets(targetParseResult)
mainVerbAlignments = self.alignPos('verb', 'v', source, target, sourceParseResult, targetParseResult, alignments)
for item in mainVerbAlignments:
if item not in alignments:
alignments.append(item)
if item[0] not in sourceWordIndicesAlreadyAligned:
sourceWordIndicesAlreadyAligned.append(item[0])
if item[1] not in targetWordIndicesAlreadyAligned:
targetWordIndicesAlreadyAligned.append(item[1])
nounAlignments = self.alignPos('noun', 'n', source, target, sourceParseResult, targetParseResult, alignments)
for item in nounAlignments:
if item not in alignments:
alignments.append(item)
if item[0] not in sourceWordIndicesAlreadyAligned:
sourceWordIndicesAlreadyAligned.append(item[0])
if item[1] not in targetWordIndicesAlreadyAligned:
targetWordIndicesAlreadyAligned.append(item[1])
adjectiveAlignments = self.alignPos('adjective', 'j', source, target, sourceParseResult, targetParseResult, alignments)
for item in adjectiveAlignments:
if item not in alignments:
alignments.append(item)
if item[0] not in sourceWordIndicesAlreadyAligned:
sourceWordIndicesAlreadyAligned.append(item[0])
if item[1] not in targetWordIndicesAlreadyAligned:
targetWordIndicesAlreadyAligned.append(item[1])
adverbAlignments = self.alignPos('adverb', 'r', source, target, sourceParseResult, targetParseResult, alignments)
for item in adverbAlignments:
if item not in alignments:
alignments.append(item)
if item[0] not in sourceWordIndicesAlreadyAligned:
sourceWordIndicesAlreadyAligned.append(item[0])
if item[1] not in targetWordIndicesAlreadyAligned:
targetWordIndicesAlreadyAligned.append(item[1])
# collect evidence from textual neighborhood for aligning content words
wordSimilarities = {}
textualNeighborhoodSimilarities = {}
sourceWordIndicesBeingConsidered = []
targetWordIndicesBeingConsidered = []
for i in sourceWordIndices:
if i in sourceWordIndicesAlreadyAligned or sourceLemmas[i-1].lower() in stopwords + punctuations + ['\'s', '\'d', '\'ll']:
continue
for j in targetWordIndices:
if j in targetWordIndicesAlreadyAligned or targetLemmas[j-1].lower() in stopwords + punctuations + ['\'s', '\'d', '\'ll']:
continue
word1 = Word(i, sourceWords[i-1], sourceLemmas[i-1], sourcePosTags[i-1], '')
word2 = Word(j, targetWords[j-1], targetLemmas[j-1], targetPosTags[j-1], '')
wordSimilarities[(i, j)] = wordRelatednessAlignment(word1, word2, self.config)
sourceWordIndicesBeingConsidered.append(i)
targetWordIndicesBeingConsidered.append(j)
# textual neighborhood similarities
sourceNeighborhood = findTextualNeighborhood(source, i, 3, 3)
targetNeighborhood = findTextualNeighborhood(target, j, 3, 3)
evidence = 0
for k in xrange(len(sourceNeighborhood[0])):
for l in xrange(len(targetNeighborhood[0])):
neighbor1 = Word(sourceNeighborhood[0][k], sourceNeighborhood[1][k], sourceLemmas[sourceNeighborhood[0][k]-1], sourcePosTags[sourceNeighborhood[0][k]-1], '')
neighbor2 = Word(targetNeighborhood[0][l], targetNeighborhood[1][l], targetLemmas[targetNeighborhood[0][l]-1], targetPosTags[targetNeighborhood[0][l]-1], '')
if (sourceNeighborhood[1][k] not in stopwords + punctuations) and ((sourceNeighborhood[0][k], targetNeighborhood[0][l]) in alignments or (wordRelatednessAlignment(neighbor1, neighbor2, self.config) >= self.config.alignment_similarity_threshold)):
evidence += wordRelatednessAlignment(neighbor1, neighbor2, self.config)
textualNeighborhoodSimilarities[(i, j)] = evidence
numOfUnalignedWordsInSource = len(set(sourceWordIndicesBeingConsidered))
# now align: find the best alignment in each iteration of the following loop and include in alignments if good enough
for item in xrange(numOfUnalignedWordsInSource):
highestWeightedSim = 0
bestWordSim = 0
bestSourceIndex = -1
bestTargetIndex = -1
for i in set(sourceWordIndicesBeingConsidered):
if i in sourceWordIndicesAlreadyAligned:
continue
for j in set(targetWordIndicesBeingConsidered):
if j in targetWordIndicesAlreadyAligned:
continue
if (i, j) not in wordSimilarities:
continue
if wordSimilarities[(i, j)] == self.config.alignment_similarity_threshold:
if wordSimilarities[(i, j)] + textualNeighborhoodSimilarities[(i, j)] <= 1.0:
continue
if self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * textualNeighborhoodSimilarities[(i, j)] > highestWeightedSim:
highestWeightedSim = self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * textualNeighborhoodSimilarities[(i, j)]
bestSourceIndex = i
bestTargetIndex = j
bestWordSim = wordSimilarities[(i, j)]
bestTextNeighborhoodSim = textualNeighborhoodSimilarities[(i, j)]
if bestWordSim >= self.config.alignment_similarity_threshold and [bestSourceIndex, bestTargetIndex] not in alignments and bestSourceIndex not in sourceWordIndicesAlreadyAligned and bestTargetIndex not in targetWordIndicesAlreadyAligned:
if sourceLemmas[bestSourceIndex-1].lower() not in stopwords:
alignments.append([bestSourceIndex, bestTargetIndex])
sourceWordIndicesAlreadyAligned.append(bestSourceIndex)
targetWordIndicesAlreadyAligned.append(bestTargetIndex)
if bestSourceIndex in sourceWordIndicesBeingConsidered:
sourceWordIndicesBeingConsidered.remove(bestSourceIndex)
if bestTargetIndex in targetWordIndicesBeingConsidered:
targetWordIndicesBeingConsidered.remove(bestTargetIndex)
# look if any remaining word is a part of a hyphenated word
for i in sourceWordIndices:
if i in sourceWordIndicesAlreadyAligned:
continue
if '-' in sourceWords[i-1] and sourceWords[i-1] != '-':
tokens = sourceWords[i-1].split('-')
commonContiguousSublists = findAllCommonContiguousSublists(tokens, targetWords)
for item in commonContiguousSublists:
if len(item[0]) == 1 and target[item[1][0]][3] not in stopwords:
for jtem in item[1]:
if [i, jtem+1] not in alignments and jtem+1 not in targetWordIndicesAlreadyAligned:
alignments.append([i, jtem+1])
sourceWordIndicesAlreadyAligned.append(i)
targetWordIndicesAlreadyAligned.append(jtem+1)
for i in targetWordIndices:
if i in targetWordIndicesAlreadyAligned:
continue
if '-' in target[i-1][2] and target[i-1][2] != '-':
tokens = target[i-1][2].split('-')
commonContiguousSublists = findAllCommonContiguousSublists(sourceWords, tokens)
for item in commonContiguousSublists:
if len(item[0]) == 1 and source[item[0][0]][3] not in stopwords:
for jtem in item[0]:
if [jtem+1, i] not in alignments and i not in targetWordIndicesAlreadyAligned:
alignments.append([jtem+1, i])
sourceWordIndicesAlreadyAligned.append(jtem+1)
targetWordIndicesAlreadyAligned.append(i)
# collect evidence from dependency neighborhood for aligning stopwords
wordSimilarities = {}
dependencyNeighborhoodSimilarities = {}
sourceWordIndicesBeingConsidered = []
targetWordIndicesBeingConsidered = []
for i in sourceWordIndices:
if sourceLemmas[i-1].lower() not in stopwords or i in sourceWordIndicesAlreadyAligned:
continue
for j in targetWordIndices:
if targetLemmas[j-1].lower() not in stopwords or j in targetWordIndicesAlreadyAligned:
continue
word1 = Word(i, sourceWords[i-1], sourceLemmas[i-1], sourcePosTags[i-1], '')
word2 = Word(j, targetWords[j-1], targetLemmas[j-1], targetPosTags[j-1], '')
if (sourceLemmas[i-1] != targetLemmas[j-1]) and (wordRelatednessAlignment(word1, word2, self.config) < self.config.alignment_similarity_threshold):
continue
wordSimilarities[(i, j)] = wordRelatednessAlignment(word1, word2, self.config)
sourceWordIndicesBeingConsidered.append(i)
targetWordIndicesBeingConsidered.append(j)
sourceWordParents = findParents(sourceDParse, i, sourceWords[i-1])
sourceWordChildren = findChildren(sourceDParse, i, sourceWords[i-1])
targetWordParents = findParents(targetDParse, j, targetWords[j-1])
targetWordChildren = findChildren(targetDParse, j, targetWords[j-1])
evidence = 0
for item in sourceWordParents:
for jtem in targetWordParents:
if [item[0], jtem[0]] in alignments:
evidence += 1
for item in sourceWordChildren:
for jtem in targetWordChildren:
if [item[0], jtem[0]] in alignments:
evidence += 1
dependencyNeighborhoodSimilarities[(i, j)] = evidence
numOfUnalignedWordsInSource = len(set(sourceWordIndicesBeingConsidered))
# now align: find the best alignment in each iteration of the following loop and include in alignments if good enough
for item in xrange(numOfUnalignedWordsInSource):
highestWeightedSim = 0
bestWordSim = 0
bestSourceIndex = -1
bestTargetIndex = -1
for i in set(sourceWordIndicesBeingConsidered):
for j in set(targetWordIndicesBeingConsidered):
if (i, j) not in wordSimilarities:
continue
if self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * dependencyNeighborhoodSimilarities[(i, j)] > highestWeightedSim:
highestWeightedSim = self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * dependencyNeighborhoodSimilarities[(i, j)]
bestSourceIndex = i
bestTargetIndex = j
bestWordSim = wordSimilarities[(i, j)]
bestDependencyNeighborhoodSim = dependencyNeighborhoodSimilarities[(i, j)]
if bestWordSim >= self.config.alignment_similarity_threshold and bestDependencyNeighborhoodSim > 0 and [bestSourceIndex, bestTargetIndex] not in alignments and bestSourceIndex not in sourceWordIndicesAlreadyAligned and bestTargetIndex not in targetWordIndicesAlreadyAligned:
alignments.append([bestSourceIndex, bestTargetIndex])
sourceWordIndicesAlreadyAligned.append(bestSourceIndex)
targetWordIndicesAlreadyAligned.append(bestTargetIndex)
if bestSourceIndex in sourceWordIndicesBeingConsidered:
sourceWordIndicesBeingConsidered.remove(bestSourceIndex)
if bestTargetIndex in targetWordIndicesBeingConsidered:
targetWordIndicesBeingConsidered.remove(bestTargetIndex)
# collect evidence from textual neighborhood for aligning stopwords and punctuations
wordSimilarities = {}
textualNeighborhoodSimilarities = {}
sourceWordIndicesBeingConsidered = []
targetWordIndicesBeingConsidered = []
for i in sourceWordIndices:
if (sourceLemmas[i-1].lower() not in stopwords + punctuations + ['\'s', '\'d', '\'ll']) or i in sourceWordIndicesAlreadyAligned:
continue
for j in targetWordIndices:
if (targetLemmas[j-1].lower() not in stopwords + punctuations + ['\'s', '\'d', '\'ll']) or j in targetWordIndicesAlreadyAligned:
continue
word1 = Word(i, sourceWords[i-1], sourceLemmas[i-1], sourcePosTags[i-1], '')
word2 = Word(j, targetWords[j-1], targetLemmas[j-1], targetPosTags[j-1], '')
if wordRelatednessAlignment(word1, word2, self.config) < self.config.alignment_similarity_threshold:
continue
wordSimilarities[(i, j)] = wordRelatednessAlignment(word1, word2, self.config)
sourceWordIndicesBeingConsidered.append(i)
targetWordIndicesBeingConsidered.append(j)
# textual neighborhood evidence, increasing evidence if content words around this stop word are aligned
evidence = 0
k = i
l = j
while k > 0:
if sourceLemmas[k-1].lower() in stopwords + punctuations + ['\'s', '\'d', '\'ll']:
k -= 1
else:
break
while l > 0:
if targetLemmas[l-1].lower() in stopwords + punctuations + ['\'s', '\'d', '\'ll']:
l -= 1
else:
break
m = i
n = j
while m < len(sourceLemmas) - 1:
if sourceLemmas[m - 1].lower() in stopwords + punctuations + ['\'s', '\'d', '\'ll']:
m += 1
else:
break
while n < len(targetLemmas) - 1:
if targetLemmas[n - 1].lower() in stopwords + punctuations + ['\'s', '\'d', '\'ll']:
n += 1
else:
break
if [k, l] in alignments:
evidence += 1
if [m, n] in alignments:
evidence += 1
textualNeighborhoodSimilarities[(i, j)] = evidence
numOfUnalignedWordsInSource = len(set(sourceWordIndicesBeingConsidered))
# now align: find the best alignment in each iteration of the following loop and include in alignments if good enough
for item in xrange(numOfUnalignedWordsInSource):
highestWeightedSim = 0
bestWordSim = 0
bestSourceIndex = -1
bestTargetIndex = -1
for i in set(sourceWordIndicesBeingConsidered):
if i in sourceWordIndicesAlreadyAligned:
continue
for j in set(targetWordIndicesBeingConsidered):
if j in targetWordIndicesAlreadyAligned:
continue
if (i, j) not in wordSimilarities:
continue
if self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * textualNeighborhoodSimilarities[(i, j)] > highestWeightedSim:
highestWeightedSim = self.config.theta * wordSimilarities[(i, j)] + (1 - self.config.theta) * textualNeighborhoodSimilarities[(i, j)]
bestSourceIndex = i
bestTargetIndex = j
bestWordSim = wordSimilarities[(i, j)]
bestTextNeighborhoodSim = textualNeighborhoodSimilarities[(i, j)]
if bestWordSim >= self.config.alignment_similarity_threshold and bestTextNeighborhoodSim > 0 and [bestSourceIndex, bestTargetIndex] not in alignments and bestSourceIndex not in sourceWordIndicesAlreadyAligned and bestTargetIndex not in targetWordIndicesAlreadyAligned:
alignments.append([bestSourceIndex, bestTargetIndex])
sourceWordIndicesAlreadyAligned.append(bestSourceIndex)
targetWordIndicesAlreadyAligned.append(bestTargetIndex)
if bestSourceIndex in sourceWordIndicesBeingConsidered:
sourceWordIndicesBeingConsidered.remove(bestSourceIndex)
if bestTargetIndex in targetWordIndicesBeingConsidered:
targetWordIndicesBeingConsidered.remove(bestTargetIndex)
alignments = [item for item in alignments if item[0] != 0 and item[1] != 0]
return alignments
def align(self, sentence1, sentence2):
sentence1ParseResult = parseText(sentence1)
sentence2ParseResult = parseText(sentence2)
sentence1LemmasAndPosTags = prepareSentence(sentence1)
sentence2LemmasAndPosTags = prepareSentence(sentence2)
myWordAlignments = sorted(self.alignWords(sentence1LemmasAndPosTags, sentence2LemmasAndPosTags, sentence1ParseResult, sentence2ParseResult), key = itemgetter(0))
myWordAlignmentTokens = [[sentence1LemmasAndPosTags[item[0]-1][2], sentence2LemmasAndPosTags[item[1]-1][2]] for item in myWordAlignments]
contextInfo = []
for pair in myWordAlignments:
sourceWord = sentence1LemmasAndPosTags[pair[0] - 1]