-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiEntityHandler.vb
1449 lines (1142 loc) · 58.1 KB
/
iEntityHandler.vb
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
Imports System.Text.RegularExpressions
Imports EntityManagement.Recognition.Classifer.EntityClassifier
Imports EntityManagement.Recognition.Classifer.EntityClassifier.Discover
Imports EntityManagement.Recognition.DataObjects
Namespace Recognition
Namespace DataObjects
Public Structure AnswerType
Public Sub New(ByVal type As String, ByVal entities As List(Of String))
Me.Type = type
Me.Entities = entities
End Sub
Public Property Entities As List(Of String)
Public Property Type As String
End Structure
Public Structure CapturedContent
Public Sub New(ByVal word As String, ByVal precedingWords As List(Of String), ByVal followingWords As List(Of String))
Me.Word = word
Me.PrecedingWords = precedingWords
Me.FollowingWords = followingWords
End Sub
Public Property FollowingWords As List(Of String)
Public Property PrecedingWords As List(Of String)
Public Property Word As String
End Structure
Public Structure CapturedWord
Public Sub New(ByVal word As String, ByVal precedingWords As List(Of String), ByVal followingWords As List(Of String), ByVal person As String, ByVal location As String)
Me.Word = word
Me.PrecedingWords = precedingWords
Me.FollowingWords = followingWords
Me.Person = person
Me.Location = location
End Sub
''' <summary>
''' Gets or sets the context words.
''' </summary>
Public Property ContextWords As List(Of String)
Public Property Entity As String
Public Property EntityType As String
''' <summary>
''' Gets or sets the entity types associated with the word.
''' </summary>
Public Property EntityTypes As List(Of String)
Public Property FollowingWords As List(Of String)
''' <summary>
''' Gets or sets a value indicating whether the word is recognized as an entity.
''' </summary>
Public Property IsEntity As Boolean
''' <summary>
''' Gets or sets a value indicating whether the word is the focus term.
''' </summary>
Public Property IsFocusTerm As Boolean
''' <summary>
''' Gets or sets a value indicating whether the word is a following word.
''' </summary>
Public Property IsFollowing As Boolean
''' <summary>
''' Gets or sets a value indicating whether the word is a preceding word.
''' </summary>
Public Property IsPreceding As Boolean
Public Property Location As String
Public Property Person As String
Public Property PrecedingWords As List(Of String)
Public Property Word As String
End Structure
Public Structure NlpReport
Public EntityLists As List(Of Entity)
Public SearchPatterns As List(Of SemanticPattern)
Public UserText As String
Public Sub New(ByRef Usertext As String, Entitylists As List(Of Entity), ByRef SearchPatterns As List(Of SemanticPattern))
Me.UserText = Usertext
Me.EntityLists = Entitylists
Me.SearchPatterns = SearchPatterns
End Sub
End Structure
Public Structure WordWithContext
''' <summary>
''' Gets or sets the context words.
''' </summary>
Public Property ContextWords As List(Of String)
''' <summary>
''' Gets or sets the entity types associated with the word.
''' </summary>
Public Property EntityTypes As List(Of String)
''' <summary>
''' Gets or sets a value indicating whether the word is recognized as an entity.
''' </summary>
Public Property IsEntity As Boolean
''' <summary>
''' Gets or sets a value indicating whether the word is the focus term.
''' </summary>
Public Property IsFocusTerm As Boolean
''' <summary>
''' Gets or sets a value indicating whether the word is a following word.
''' </summary>
Public Property IsFollowing As Boolean
''' <summary>
''' Gets or sets a value indicating whether the word is a preceding word.
''' </summary>
Public Property IsPreceding As Boolean
''' <summary>
''' Gets or sets the captured word.
''' </summary>
Public Property Word As String
End Structure
End Namespace
Public Class ICollect
Public Shared FemaleNames As List(Of String)
Public Shared MaleNames As List(Of String)
Public Shared ObjectNames As List(Of String)
Private Shared commonQuestionHeaders As List(Of String)
Private Shared iPronouns As List(Of String)
'' Example entity list to search
'Dim entityList As New List(Of String)() From {"dolphins"}
Private Shared questionWords As List(Of String)
Private Shared semanticPatterns As List(Of String)
Private conclusions As List(Of String)
Private hypotheses As List(Of String)
Private patterns As Dictionary(Of String, String)
Private premises As List(Of String)
''' <summary>
''' Returns all Pronouns in the model
''' </summary>
''' <returns></returns>
Public Shared ReadOnly Property Pronouns As List(Of String)
Get
Dim Lst As New List(Of String)
Lst.AddRange(MaleNames)
Lst.AddRange(FemaleNames)
Lst.AddRange(ObjectNames)
Lst.AddRange(iPronouns)
Return Lst.Distinct.ToList
End Get
End Property
Public Shared Property bornInPattern As String = "\b([A-Z][a-z]+)\b relation \(born in\) \b([A-Z][a-z]+)\b"
Public Shared Property datePattern As String = "\b\d{4}\b"
Public Shared Property organizationPattern As String = "\b([A-Z][a-z]+)\b"
' Regular expression patterns for different entity types
Public Shared Property personPattern As String = "\b([A-Z][a-z]+)\b"
Public Shared Property programmingLanguagePattern As String = "\b[A-Z][a-z]+\.[a-z]+\b"
Public Shared Property wroteBookPattern As String = "\b([A-Z][a-z]+)\b \(wrote a book called\) \b([A-Z][a-z]+)\b"
Public Shared Function CaptureWordsWithContext(text As String, entityList As List(Of String), contextWords As Integer) As List(Of String)
Dim words As String() = text.Split(" "c)
Dim capturedWords As New List(Of String)()
For i As Integer = 0 To words.Length - 1
Dim word As String = words(i)
If entityList.Contains(word) Then
Dim startIndex As Integer = Math.Max(0, i - contextWords)
Dim endIndex As Integer = Math.Min(words.Length - 1, i + contextWords)
Dim capturedWord As String = String.Join(" ", words, startIndex, endIndex - startIndex + 1)
capturedWords.Add(capturedWord)
End If
Next
Return capturedWords
End Function
''' <summary>
''' Detects entities in the given text.
''' </summary>
''' <param name="text">The text to be analyzed.</param>
''' <param name="EntityList">A list of entities to detect.</param>
''' <returns>A list of detected entities in the text.</returns>
Public Shared Function Detect(ByRef text As String, ByRef EntityList As List(Of String)) As List(Of String)
Dim Lst As New List(Of String)
If text Is Nothing Then
Throw New ArgumentNullException("text")
End If
If EntityList Is Nothing Then
Throw New ArgumentNullException("EntityList")
End If
If Classifer.EntityClassifier.Detect.DetectEntity(text, EntityList) = True Then
For Each item In EntityList
If text.Contains(item) Then
Lst.Add(item)
End If
Next
Return Lst
Else
Return New List(Of String)
End If
End Function
''' <summary>
''' Attempts to find Unknown Names(pronouns) identified by thier capitalization
''' </summary>
''' <param name="words"></param>
''' <returns></returns>
Public Shared Function DetectNamedEntities(ByVal words() As String) As List(Of String)
Dim namedEntities As New List(Of String)
For i = 0 To words.Length - 1
Dim word = words(i)
If Char.IsUpper(word(0)) AndAlso Not Pronouns.Contains(word.ToLower()) Then
namedEntities.Add(word)
End If
Next
Return namedEntities
End Function
Public Shared Function ExtractAdjectivePhrases(taggedWords As List(Of KeyValuePair(Of String, String))) As List(Of String)
Dim adjectivePhrases As New List(Of String)()
Dim currentPhrase As String = ""
Dim insideAdjectivePhrase As Boolean = False
For Each taggedWord In taggedWords
Dim word As String = taggedWord.Key
Dim tag As String = taggedWord.Value
If tag.StartsWith("JJ") Then ' Adjective tag
If insideAdjectivePhrase Then
currentPhrase += " " & word
Else
currentPhrase = word
insideAdjectivePhrase = True
End If
Else
If insideAdjectivePhrase Then
adjectivePhrases.Add(currentPhrase)
insideAdjectivePhrase = False
End If
End If
Next
' Add the last phrase if it is an adjective phrase
If insideAdjectivePhrase Then
adjectivePhrases.Add(currentPhrase)
End If
Return adjectivePhrases
End Function
''' <summary>
''' Extracts context Entitys , As Well As thier context words
''' </summary>
''' <param name="itext"></param>
''' <param name="contextSize"></param>
''' <param name="entities">Values to retrieve context for</param>
''' <returns></returns>
Public Shared Function ExtractCapturedContextIntext(ByRef itext As String, ByVal contextSize As Integer, ByRef entities As List(Of String)) As List(Of CapturedContent)
Dim wordsWithContext As New List(Of CapturedContent)
' Create a regular expression pattern for matching the entities
Dim pattern As String = "(" + String.Join("|", entities.Select(Function(e) Regex.Escape(e))) + ")"
' Add context placeholders to the pattern
Dim contextPattern As String = "(?:\S+\s+){" + contextSize.ToString() + "}"
' Combine the entity pattern and the context pattern
pattern = contextPattern + "(" + pattern + ")" + contextPattern
' Find all matches in the text
Dim matches As MatchCollection = Regex.Matches(itext, pattern)
' Iterate over the matches and extract the words with context
For Each match As Match In matches
Dim sequence As String = match.Value.Trim()
Dim word As String = match.Groups(1).Value.Trim()
Dim precedingContext As String = match.Groups(2).Value.Trim()
Dim followingContext As String = match.Groups(3).Value.Trim()
Dim precedingWords As List(Of String) = Split(precedingContext, " "c, StringSplitOptions.RemoveEmptyEntries).ToList
Dim followingWords As List(Of String) = Split(followingContext, " "c, StringSplitOptions.RemoveEmptyEntries).ToList
Dim capturedWord As New CapturedContent(word, precedingWords, followingWords)
wordsWithContext.Add(capturedWord)
Next
Return wordsWithContext
End Function
Public Shared Function ExtractNounPhrases(taggedWords As List(Of KeyValuePair(Of String, String))) As List(Of String)
Dim nounPhrases As New List(Of String)()
Dim currentPhrase As String = ""
Dim insideNounPhrase As Boolean = False
For Each taggedWord In taggedWords
Dim word As String = taggedWord.Key
Dim tag As String = taggedWord.Value
If tag.StartsWith("NN") Then ' Noun tag
If insideNounPhrase Then
currentPhrase += " " & word
Else
currentPhrase = word
insideNounPhrase = True
End If
Else
If insideNounPhrase Then
nounPhrases.Add(currentPhrase)
insideNounPhrase = False
End If
End If
Next
' Add the last phrase if it is a noun phrase
If insideNounPhrase Then
nounPhrases.Add(currentPhrase)
End If
Return nounPhrases
End Function
''' <summary>
''' Extracts patterns from the text and replaces detected entities with asterisks.
''' </summary>
''' <param name="text">The text to extract patterns from.</param>
''' <param name="EntityList">A list of entities to detect and replace.</param>
''' <returns>The extracted pattern with detected entities replaced by asterisks.</returns>
Public Shared Function ExtractPattern(ByRef text As String, ByRef EntityList As List(Of String)) As String
If text Is Nothing Then
Throw New ArgumentNullException("text")
End If
If EntityList Is Nothing Then
Throw New ArgumentNullException("EntityList")
End If
Dim Entitys As New List(Of String)
Dim Str As String = text
If Classifer.EntityClassifier.Detect.DetectEntity(text, EntityList) = True Then
Entitys = Classifer.EntityClassifier.Detect.DetectEntitysInText(text, EntityList)
Str = Classifer.EntityClassifier.Discover.DiscoverShape(Str, Entitys)
Str = Classifer.EntityClassifier.Transform.TransformText(Str, Entitys)
End If
Return Str
End Function
Public Shared Function ExtractVerbPhrases(taggedWords As List(Of KeyValuePair(Of String, String))) As List(Of String)
Dim verbPhrases As New List(Of String)()
Dim currentPhrase As String = ""
Dim insideVerbPhrase As Boolean = False
For Each taggedWord In taggedWords
Dim word As String = taggedWord.Key
Dim tag As String = taggedWord.Value
If tag.StartsWith("VB") Then ' Verb tag
If insideVerbPhrase Then
currentPhrase += " " & word
Else
currentPhrase = word
insideVerbPhrase = True
End If
Else
If insideVerbPhrase Then
verbPhrases.Add(currentPhrase)
insideVerbPhrase = False
End If
End If
Next
' Add the last phrase if it is a verb phrase
If insideVerbPhrase Then
verbPhrases.Add(currentPhrase)
End If
Return verbPhrases
End Function
''' <summary>
''' Returns a List of WordsWithCOntext with the Focus word at the center surrounded by its context words,
''' it can be a useful pattern chunk which can be used for prediction as a context ngram (min-3)
''' </summary>
''' <param name="text"></param>
''' <param name="focusTerm"></param>
''' <param name="precedingWordsCount"></param>
''' <param name="followingWordsCount"></param>
''' <returns></returns>
Public Shared Function ExtractWordsWithContext(text As String, focusTerm As String, precedingWordsCount As Integer, followingWordsCount As Integer) As List(Of WordWithContext)
Dim words As List(Of String) = text.Split(" "c).ToList()
Dim focusIndex As Integer = words.IndexOf(focusTerm)
Dim capturedWordsWithEntityContext As New List(Of WordWithContext)()
If focusIndex <> -1 Then
Dim startIndex As Integer = Math.Max(0, focusIndex - precedingWordsCount)
Dim endIndex As Integer = Math.Min(words.Count - 1, focusIndex + followingWordsCount)
For i As Integer = startIndex To endIndex
Dim word As String = words(i)
Dim wordWithContext As New WordWithContext() With {
.Word = word,
.IsFocusTerm = (i = focusIndex),
.IsPreceding = (i < focusIndex),
.IsFollowing = (i > focusIndex)
}
capturedWordsWithEntityContext.Add(wordWithContext)
Next
End If
Return capturedWordsWithEntityContext
End Function
''' <summary>
''' Returns a new string with the Focus word at the center surrounded by its context words,
''' it can be a useful pattern chunk which can be used for prediction as a context ngram (min-3)
''' </summary>
''' <param name="text"></param>
''' <param name="Word"></param>
''' <param name="contextWords"></param>
''' <returns></returns>
Public Shared Function ExtractWordWithContext(text As String, Word As String, contextWords As Integer) As String
Dim words As String() = text.Split(" "c)
Dim capturedWord As String = ""
For i As Integer = 0 To words.Length - 1
Dim Tword As String = words(i)
If Word = Tword Then
Dim startIndex As Integer = Math.Max(0, i - contextWords)
Dim endIndex As Integer = Math.Min(words.Length - 1, i + contextWords)
capturedWord = String.Join(" ", words, startIndex, endIndex - startIndex + 1)
End If
Next
Return capturedWord
End Function
'1. Objects:
' - Objects are typically referred to using nouns. Examples include "car," "book," "tree," "chair," "pen," etc.
' - Objects may have specific attributes or characteristics associated with them, such as color, size, shape, etc., which can be mentioned when referring to them.
Public Shared Function FindAntecedent(words As String(), pronounIndex As Integer, entityList As List(Of String)) As String
For i As Integer = pronounIndex - 1 To 0 Step -1
Dim word As String = words(i)
If entityList.Contains(word) Then
Return word
End If
Next
Return ""
End Function
Public Shared Function FindNounPhrases(sentence As String) As List(Of String)
Dim nounPhrases As New List(Of String)()
' Split the sentence into individual words
Dim words() As String = sentence.Split({" "}, StringSplitOptions.RemoveEmptyEntries)
' Identify noun phrases
For i As Integer = 0 To words.Length - 1
If IsNoun(words(i)) Then
Dim nounPhrase As String = words(i)
Dim j As Integer = i + 1
' Combine consecutive words until a non-noun word is encountered
While j < words.Length AndAlso IsNoun(words(j))
nounPhrase += " " & words(j)
j += 1
End While
nounPhrases.Add(nounPhrase)
End If
Next
Return nounPhrases
End Function
Public Shared Function FindPhrases(sentence As String, phraseType As String) As List(Of String)
Dim phrases As New List(Of String)()
' Split the sentence into individual words
Dim words() As String = sentence.Split({" "}, StringSplitOptions.RemoveEmptyEntries)
' Identify phrases based on the specified type
For i As Integer = 0 To words.Length - 1
Dim currentWord As String = words(i)
If (phraseType = "verb" AndAlso IsVerb(currentWord)) OrElse
(phraseType = "adjective" AndAlso IsAdjective(currentWord)) Then
Dim phrase As String = currentWord
Dim j As Integer = i + 1
' Combine consecutive words until a non-phrase word is encountered
While j < words.Length AndAlso (IsVerb(words(j)) OrElse IsAdjective(words(j)))
phrase += " " & words(j)
j += 1
End While
phrases.Add(phrase)
End If
Next
Return phrases
End Function
Public Shared Function FindPhrases(taggedWords As List(Of KeyValuePair(Of String, String)), phraseType As String) As List(Of String)
Dim phrases As New List(Of String)()
' Identify phrases based on the specified type
For i As Integer = 0 To taggedWords.Count - 1
Dim currentWord As String = taggedWords(i).Key
Dim currentTag As String = taggedWords(i).Value
If (phraseType = "verb" AndAlso IsVerbTag(currentTag)) OrElse
(phraseType = "adjective" AndAlso IsAdjectiveTag(currentTag)) Then
Dim phrase As String = currentWord
Dim j As Integer = i + 1
' Combine consecutive words until a non-phrase word is encountered
While j < taggedWords.Count AndAlso (IsVerbTag(taggedWords(j).Value) OrElse IsAdjectiveTag(taggedWords(j).Value))
phrase += " " & taggedWords(j).Key
j += 1
End While
phrases.Add(phrase)
End If
Next
Return phrases
End Function
'2. Locations:
' - Locations are places or areas where entities or objects exist or are situated.
' - Locations can be referred to using nouns that represent specific places, such as "home," "office," "school," "park," "store," "gym," "library," etc.
' - Locations can also be described using adjectives or prepositional phrases, such as "in the backyard," "at the beach," "on the street," "near the river," etc.
Public Shared Function GetPronoun(word As String) As String
' Add mapping of pronouns to words as needed
Select Case word
Case "he"
Return "him"
Case "she"
Return "her"
Case "it"
Return "its"
Case "they"
Return "them"
Case "them"
Return "them"
Case "that"
Return "that"
Case Else
Return ""
End Select
End Function
'3. Antecedents:
' - Antecedents are the entities or objects that are referred to by pronouns or other referencing words in a sentence.
' - Antecedents are typically introduced in a sentence before the pronoun or referencing word. For example, "John went to the store. He bought some groceries."
' - Antecedents can be humans, objects, animals, or other entities. The choice of pronouns or referencing words depends on the gender and type of the antecedent. For example, "he" for a male, "she" for a female, "it" for an object, and "they" for multiple entities.
''' <summary>
''' Pronoun_mapping to normailized value
''' </summary>
''' <param name="word"></param>
''' <returns></returns>
Public Shared Function GetPronounIndicator(word As String) As String
' Add mapping of pronouns to words as needed
Select Case word
Case "shes"
Return "her"
Case "his"
Return "him"
Case "hers"
Return "her"
Case "her"
Return "her"
Case "him"
Return "him"
Case "he"
Return "him"
Case "she"
Return "her"
Case "its"
Return " it"
Case "it"
Return " it"
Case "they"
Return "them"
Case "thats"
Return "that"
Case "that"
Return "that"
Case "we"
Return "we"
Case "us"
Return "us"
Case "them"
Return "them"
Case Else
Return ""
End Select
End Function
Public Shared Function IsAdjective(word As String) As Boolean
' Add your own adjective identification logic here
' This is a basic example that checks if the word ends with "ly"
Return word.EndsWith("ly")
End Function
Public Shared Function IsAdjectiveTag(tag As String) As Boolean
' Add your own adjective tag identification logic here
' This is a basic example that checks if the tag starts with "JJ"
Return tag.StartsWith("JJ")
End Function
Public Shared Function IsAntecedentIndicator(ByVal token As String) As Boolean
' List of antecedent indicator words
Dim antecedentIndicators As String() = {" he", "she", "it", "they", "them", "that", "him", "we", "us", "its", "his", "thats"}
' Check if the token is an antecedent indicator
Return antecedentIndicators.Contains(token.ToLower())
End Function
Public Shared Function IsConclusion(ByVal sentence As String) As Boolean
' List of indicator phrases for conclusions
Dim conclusionIndicators As String() = {"therefore", "thus", "consequently", "hence", "in conclusion"}
' Check if any of the conclusion indicators are present in the sentence
For Each indicator In conclusionIndicators
If sentence.Contains(indicator) Then
Return True
End If
Next
Return False
End Function
Public Shared Function IsEntityOrPronoun(word As String, ByRef Entitys As List(Of String)) As Boolean
Dim AntecedantIdentifers() As String = {" he ", "she", "him", "her", "it", "them", "they", "that", "we"}
' 1.For simplicity, let's assume any word ending with "s" is a noun/pronoun
' 2.For simplicity, let's assume any word referring to a person is a pronoun
Dim lowerCaseWord As String = word.ToLower()
For Each item In Entitys
If item.ToLower = lowerCaseWord Then Return True
Next
For Each item In AntecedantIdentifers
If item.ToLower = lowerCaseWord Then Return True
Next
Return False
End Function
Public Shared Function IsFemaleNounOrPronoun(ByVal word As String) As Boolean
Dim ifemaleNouns() As String = {"she", "her", "hers", "shes"}
Return FemaleNames.Contains(word.ToLower()) OrElse FemaleNames.Contains(word.ToLower() & "s") OrElse ifemaleNouns.Contains(word.ToLower)
End Function
''' <summary>
''' female names
''' </summary>
''' <param name="pronoun"></param>
''' <returns></returns>
Public Shared Function IsFemalePronoun(pronoun As String) As Boolean
Dim lowerCasePronoun As String = pronoun.ToLower()
Return lowerCasePronoun = "her" OrElse lowerCasePronoun = "she" OrElse lowerCasePronoun = "hers" OrElse FemaleNames.Contains(pronoun)
End Function
Public Shared Function IsMaleNounOrPronoun(ByVal word As String) As Boolean
Dim imaleNouns() As String = {"him", " he", "his", ""}
Return MaleNames.Contains(word.ToLower()) OrElse imaleNouns.Contains(word.ToLower)
End Function
''' <summary>
''' Malenames
''' </summary>
''' <param name="pronoun"></param>
''' <returns></returns>
Public Shared Function IsMalePronoun(pronoun As String) As Boolean
Dim lowerCasePronoun As String = pronoun.ToLower()
Return lowerCasePronoun = " he" OrElse lowerCasePronoun = "him" OrElse lowerCasePronoun = " his" OrElse MaleNames.Contains(pronoun)
End Function
Public Shared Function IsNoun(word As String) As Boolean
' Add your own noun identification logic here
' You can check for patterns, word lists, or use external resources for more accurate noun detection
' This is a basic example that only checks for the first letter being uppercase
Return Char.IsUpper(word(0))
End Function
Public Shared Function IsObjectPronoun(ByVal word As String) As Boolean
Dim iObjectNames() As String = {"its", "it", "that", "thats"}
Return iObjectNames.Contains(word.ToLower()) OrElse iObjectNames.Contains(word.ToLower() & "s")
End Function
'Possible Output: "The person associated with John is..."
Public Shared Function IsPersonName(word As String) As Boolean
' Implement your custom logic to determine if a word is a person name
' Return true if the word is a person name, false otherwise
' Example: Check if the word starts with an uppercase letter
Return Char.IsUpper(word(0))
End Function
Public Shared Function IsPremise(ByVal sentence As String) As Boolean
' List of indicator phrases for premises
Dim premiseIndicators As String() = {"based on", "according to", "given", "assuming", "since"}
' Check if any of the premise indicators are present in the sentence
For Each indicator In premiseIndicators
If sentence.Contains(indicator) Then
Return True
End If
Next
Return False
End Function
Public Shared Function IsProperNoun(word As String) As Boolean
' Implement your custom logic to determine if a word is a proper noun
' Return true if the word is a proper noun, false otherwise
' Example: Check if the word starts with an uppercase letter
Return Char.IsUpper(word(0))
End Function
Public Shared Function IsQuestion(sentence As String) As Boolean
' Preprocess the sentence
sentence = sentence.ToLower().Trim()
' Check for question words
If StartsWithAny(sentence, questionWords) Then
Return True
End If
' Check for question marks
If sentence.EndsWith("?") Then
Return True
End If
' Check for semantic patterns
Dim patternRegex As New Regex(String.Join("|", semanticPatterns))
If patternRegex.IsMatch(sentence) Then
Return True
End If
' Check for common question headers
If StartsWithAny(sentence, commonQuestionHeaders) Then
Return True
End If
' No matching question pattern found
Return False
End Function
Public Shared Function IsVerb(word As String) As Boolean
' Add your own verb identification logic here
' This is a basic example that checks if the word ends with "ing"
Return word.EndsWith("ing")
End Function
Public Shared Function IsVerbTag(tag As String) As Boolean
' Add your own verb tag identification logic here
' This is a basic example that checks if the tag starts with "V"
Return tag.StartsWith("V")
End Function
Public Shared Function MatchesAnswerShape(sentence As String, answerShapes As List(Of String)) As Boolean
' Check if the sentence matches any of the answer shapes using regex pattern matching
For Each answerShape In answerShapes
Dim pattern As String = "\b" + Regex.Escape(answerShape) + "\b"
If Regex.IsMatch(sentence, pattern, RegexOptions.IgnoreCase) Then
Return True
End If
Next
Return False
End Function
' Identify antecedent indicators:
' - Look for pronouns or referencing words like "he," "she," "it," "they," "them," "that" in the sentence.
' - Check the preceding tokens to identify the most recent entity token with a matching type.
' - Use the identified entity as the antecedent indicator.
''' <summary>
''' finds pronoun antecedants in the text a replaces them with thier names
''' </summary>
''' <param name="sentence"></param>
''' <param name="entityList"></param>
''' <returns></returns>
Public Shared Function ResolveCoreference(sentence As String, entityList As List(Of String)) As String
Dim words As String() = sentence.Split(" ")
For i As Integer = 0 To words.Length - 1
Dim word As String = words(i)
If entityList.Contains(word) Then
Dim pronoun As String = GetPronoun(word)
Dim antecedent As String = FindAntecedent(words, i, entityList)
If Not String.IsNullOrEmpty(antecedent) Then
sentence = sentence.Replace(pronoun, antecedent)
End If
End If
Next
Return sentence
End Function
Public Function DetectGender(name As String) As String
' For simplicity, let's assume any name starting with a vowel is female, and the rest are male
If IsObjectPronoun(name) Then
Return "Object"
ElseIf IsMaleNounOrPronoun(name) Then
Return "Male"
ElseIf IsFemaleNounOrPronoun(name) Then
Return "Female"
Else
Return "Unknown"
End If
End Function
''' <summary>
''' Given an Answer shape , Detect and
''' Extract All Answers and context sentences
''' </summary>
''' <param name="text"></param>
''' <param name="answerShapes"></param>
''' <param name="contextSentences"></param>
''' <returns></returns>
Public Function ExtractAnswersWithContextFromText(text As String, answerShapes As List(Of String), contextSentences As Integer) As List(Of String)
Dim answers As New List(Of String)()
' Split the text into sentences
Dim sentences As String() = Split(text, ".", StringSplitOptions.RemoveEmptyEntries)
' Iterate through each sentence and check for potential answer sentences
For i As Integer = 0 To sentences.Length - 1
Dim sentence As String = sentences(i).Trim()
' Check if the sentence matches any of the answer shapes
If MatchesAnswerShape(sentence, answerShapes) Then
' Add the current sentence and the context sentences to the list of potential answer sentences
Dim startIndex As Integer = Math.Max(0, i - contextSentences)
Dim endIndex As Integer = Math.Min(i + contextSentences, sentences.Length - 1)
Dim answer As String = String.Join(" ", sentences, startIndex, endIndex - startIndex + 1).Trim()
answers.Add(answer)
End If
Next
Return answers
End Function
''' <summary>
''' catches words , context etc by entitys and concat context chunk
''' </summary>
''' <param name="text"></param>
''' <param name="entities"></param>
''' <param name="contextSize"></param>
''' <returns>complex object</returns>
Public Function ExtractCapturedContextMatchesInTextByContext(ByVal text As String, ByVal entities As List(Of String),
ByVal contextSize As Integer) As List(Of (Word As String, PrecedingWords As List(Of String), FollowingWords As List(Of String), Position As Integer))
Dim wordsWithContext As New List(Of (Word As String, PrecedingWords As List(Of String), FollowingWords As List(Of String), Position As Integer))
' Create a regular expression pattern for matching the entities
Dim pattern As String = "(" + String.Join("|", entities.Select(Function(e) Regex.Escape(e))) + ")"
' Add context placeholders to the pattern
Dim contextPattern As String = "(?:\S+\s+){" + contextSize.ToString() + "}"
' Combine the entity pattern and the context pattern
pattern = contextPattern + "(" + pattern + ")" + contextPattern
' Find all matches in the text
Dim matches As MatchCollection = Regex.Matches(text, pattern)
' Iterate over the matches and extract the words with context and position
For Each match As Match In matches
Dim wordWithContext As String = match.Groups(0).Value.Trim()
Dim word As String = match.Groups(1).Value.Trim()
Dim precedingContext As String = match.Groups(2).Value.Trim()
Dim followingContext As String = match.Groups(3).Value.Trim()
Dim position As Integer = match.Index
Dim precedingWords As List(Of String) = Split(precedingContext, " "c, StringSplitOptions.RemoveEmptyEntries).ToList()
Dim followingWords As List(Of String) = Split(followingContext, " "c, StringSplitOptions.RemoveEmptyEntries).ToList()
wordsWithContext.Add((word, precedingWords, followingWords, position))
Next
Return wordsWithContext
End Function
''' <summary>
''' Creates A context item based item the inputs and searches for matches
''' returning the item plus its context and entitys etc
''' </summary>
''' <param name="itext"></param>
''' <param name="contextSize"></param>
''' <param name="entities"></param>
''' <returns></returns>
Public Function ExtractCapturedWordsinTextByContext(ByRef itext As String, ByVal contextSize As Integer, ByRef entities As List(Of String)) As List(Of CapturedWord)
Dim wordsWithContext As New List(Of CapturedWord)()
' Create a regular expression pattern for matching the entities
Dim pattern As String = "(" + String.Join("|", entities.Select(Function(e) Regex.Escape(e))) + ")"
' Add context placeholders to the pattern
Dim contextPattern As String = "(?:\S+\s+){" + contextSize.ToString() + "}"
' Combine the entity pattern and the context pattern
pattern = contextPattern + "(" + pattern + ")" + contextPattern
' Find all matches in the text
Dim matches As MatchCollection = Regex.Matches(itext, pattern)
' Iterate over the matches and extract the words with context
For Each match As Match In matches
Dim sequence As String = match.Value.Trim()
Dim word As String = match.Groups(1).Value.Trim()
Dim precedingContext As String = match.Groups(2).Value.Trim()
Dim followingContext As String = match.Groups(3).Value.Trim()
Dim precedingWords As List(Of String) = Split(precedingContext, " "c, StringSplitOptions.RemoveEmptyEntries).ToList
Dim followingWords As List(Of String) = Split(followingContext, " "c, StringSplitOptions.RemoveEmptyEntries).ToList
Dim capturedWord As New CapturedWord(word, precedingWords, followingWords, "", "")
wordsWithContext.Add(capturedWord)
Next
Return wordsWithContext
End Function
Public Function ExtractPotentialAnswers(text As String, resolvedAntecedents As List(Of String), resolvedEntities As List(Of String)) As List(Of String)
Dim answers As New List(Of String)()
' Split the text into sentences
Dim sentences As String() = Split(text, ".", StringSplitOptions.RemoveEmptyEntries)
' Iterate through each sentence and check for potential answer sentences