-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentity_extractor.py
More file actions
1627 lines (1367 loc) · 74.1 KB
/
Copy pathentity_extractor.py
File metadata and controls
1627 lines (1367 loc) · 74.1 KB
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
"""
Advanced Entity Extraction System for TOMAS Chatbot
==================================================
This module provides sophisticated NLP-based entity extraction capabilities
to identify and extract meaningful information from user queries including:
- Person names (parents, children, staff)
- Grade levels and academic terms
- Subjects and curriculum topics
- Dates and time expressions
- School-specific terminology
- Contact information
"""
import os
import nltk
# Point NLTK to the local nltk_data folder first, then Render path for deployment
local_nltk_path = os.path.join(os.path.dirname(__file__), "nltk_data")
render_nltk_path = "/opt/render/nltk_data"
# Add local path first (for development), then Render path (for deployment)
nltk.data.path.insert(0, local_nltk_path)
nltk.data.path.append(render_nltk_path)
import re
import time
import logging
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime, timedelta
import calendar
from functools import lru_cache
# Initialize NLTK immediately like in the earlier working builds
NLTK_AVAILABLE = False
NLTK_INITIALIZED = False
# Initialize NLTK functions as None - will be set during initialization
word_tokenize = None
sent_tokenize = None
pos_tag = None
ne_chunk = None
Tree = None
def _initialize_nltk():
"""Initialize NLTK safely with error handling"""
global NLTK_AVAILABLE, NLTK_INITIALIZED
global word_tokenize, sent_tokenize, pos_tag, ne_chunk, Tree
if NLTK_INITIALIZED:
return NLTK_AVAILABLE
try:
import nltk
from nltk.tokenize import word_tokenize as _word_tokenize, sent_tokenize as _sent_tokenize
from nltk.corpus import stopwords
from nltk.tag import pos_tag as _pos_tag
from nltk.chunk import ne_chunk as _ne_chunk
from nltk.tree import Tree as _Tree
# Set global variables
word_tokenize = _word_tokenize
sent_tokenize = _sent_tokenize
pos_tag = _pos_tag
ne_chunk = _ne_chunk
Tree = _Tree
NLTK_AVAILABLE = True
NLTK_INITIALIZED = True
print("✅ NLTK initialized successfully for entity extraction")
return True
except ImportError:
NLTK_AVAILABLE = False
NLTK_INITIALIZED = True
print("NLTK not available for entity extraction")
return False
except Exception as e:
NLTK_AVAILABLE = False
NLTK_INITIALIZED = True
print(f"NLTK initialization failed: {e}")
return False
# Multilingual NLP engine removed - using rule-based entity extraction only
MULTILINGUAL_NLP_AVAILABLE = False
logger = logging.getLogger(__name__)
@dataclass
class ExtractedEntity:
"""Represents an entity extracted from user input"""
entity_type: str # person_name, grade_level, subject, date, etc.
value: str # The actual extracted value
confidence: float # Confidence score 0.0-1.0
start_pos: int = 0
end_pos: int = 0
context: str = "" # Surrounding context for disambiguation
class LightweightEntityExtractor:
"""
Fast, lightweight entity extraction using regex patterns and caching
"""
def __init__(self):
# Pre-compiled regex patterns for performance
self.patterns = {
'PERSON': re.compile(r'(?:Mr|Mrs|Ms|Dr|Prof)\.?\s+([A-Z][a-z]+)', re.I),
'LOCATION': re.compile(r'\b(?:in|at|from|to|visit|located)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)', re.I),
'ORG': re.compile(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:Corp|Inc|University|School|Elementary)', re.I),
'NAME_INTRO': re.compile(r'\b(?:my name is|i am|call me)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b', re.I),
'GRADE': re.compile(r'\b(?:grade|g\.)\s*(\d+)\b', re.I),
'SUBJECT': re.compile(r'\b(?:math|science|english|filipino|art|music|pe|physical education)\b', re.I),
'SCHOOL_NAME': re.compile(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:Elementary|School|University|College)\b', re.I),
'CITY': re.compile(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:City|Town|Province|State)\b', re.I)
}
# Blacklist to filter out common false positives
self.blacklist = {'Contact', 'Talk', 'Meet', 'The', 'I', 'You', 'We', 'They', 'This', 'That', 'Here', 'There'}
# School-specific terms
self.school_terms = {
'principal', 'teacher', 'student', 'school', 'classroom', 'library', 'cafeteria',
'gymnasium', 'office', 'adviser', 'counselor', 'nurse', 'janitor', 'security'
}
@lru_cache(maxsize=500)
def extract(self, text: str) -> List[Tuple[str, str]]:
"""
Extract entities using lightweight regex patterns with caching
Args:
text: Input text to analyze
Returns:
List of (entity_value, entity_type) tuples
"""
entities = []
for entity_type, pattern in self.patterns.items():
for match in pattern.finditer(text):
entity = match.group(1).strip() if match.groups() else match.group(0).strip()
# Filter out blacklisted entities
if entity not in self.blacklist and len(entity) > 1:
# Additional validation for school context
if self._is_valid_entity(entity, entity_type, text):
entities.append((entity, entity_type))
return entities
def _is_valid_entity(self, entity: str, entity_type: str, context: str) -> bool:
"""Validate entity based on context and type"""
context_lower = context.lower()
entity_lower = entity.lower()
# Skip very short entities
if len(entity) < 2:
return False
# Skip common words that aren't entities
common_words = {'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'}
if entity_lower in common_words:
return False
# Type-specific validation
if entity_type == 'PERSON':
# Must be capitalized and not a common word
return entity[0].isupper() and entity_lower not in common_words
elif entity_type == 'LOCATION':
# Must be capitalized and not a preposition
prepositions = {'in', 'at', 'from', 'to', 'on', 'by', 'with', 'for'}
return entity[0].isupper() and entity_lower not in prepositions
elif entity_type == 'ORG':
# Must contain organization indicators
org_indicators = {'school', 'university', 'college', 'corp', 'inc', 'ltd', 'company'}
return any(indicator in entity_lower for indicator in org_indicators)
elif entity_type == 'SUBJECT':
# Must be a known academic subject
subjects = {'math', 'mathematics', 'science', 'english', 'filipino', 'art', 'music', 'pe', 'physical education'}
return entity_lower in subjects
elif entity_type == 'SCHOOL_NAME':
# Must be capitalized and contain school indicators
school_indicators = {'elementary', 'school', 'university', 'college', 'academy'}
return entity[0].isupper() and any(indicator in entity_lower for indicator in school_indicators)
elif entity_type == 'CITY':
# Must be capitalized and contain location indicators
location_indicators = {'city', 'town', 'province', 'state', 'municipality'}
return entity[0].isupper() and any(indicator in entity_lower for indicator in location_indicators)
elif entity_type == 'GRADE':
# Must be a valid grade number
try:
grade_num = int(entity)
return 1 <= grade_num <= 12
except ValueError:
return False
return True
class AdvancedEntityExtractor:
"""
Advanced entity extraction using NLP techniques and domain-specific patterns
"""
def __init__(self):
# Initialize lightweight extractor for fast processing
self.lightweight_extractor = LightweightEntityExtractor()
self.grade_patterns = self._build_grade_patterns()
self.subject_patterns = self._build_subject_patterns()
self.name_patterns = self._build_name_patterns()
self.date_patterns = self._build_date_patterns()
self.contact_patterns = self._build_contact_patterns()
self.school_terms = self._build_school_terminology()
# Smart NLTK configuration
self.nltk_loaded = False
self._nltk_cache = {}
self._cache_timeout = 300 # 5 minutes
self._performance_stats = {
'total_queries': 0,
'nltk_queries': 0,
'cache_hits': 0,
'avg_time_ms': 0
}
# Pre-compile regex patterns for performance
self._name_patterns = [
r'\b(?:my name is|i am|call me)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b',
r'\b(?:dr\.|mr\.|mrs\.|ms\.|professor|prof\.)\s+([A-Z][a-z]+)\b',
r'\b(?:meet with|talk to|contact)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b'
]
self._compiled_patterns = [re.compile(pattern, re.IGNORECASE) for pattern in self._name_patterns]
# Entity detection triggers
self._nltk_triggers = [
r'\b(?:my name is|i am)\s+[A-Z][a-z]+\s+[A-Z][a-z]+\b',
r'\b(?:dr\.|mr\.|mrs\.|ms\.|professor|prof\.)\s+[A-Z][a-z]+\b',
r'\b(?:visit|go to|located in)\s+[A-Z][a-z]+\s+[A-Z][a-z]+\b',
r'\b(?:corporation|company|organization|school|university)\b'
]
self._compiled_triggers = [re.compile(pattern, re.IGNORECASE) for pattern in self._nltk_triggers]
def extract_entities(self, text: str, intent_context: str = None) -> List[ExtractedEntity]:
"""
Extract all entities from the given text using lightweight regex first, then advanced patterns
Args:
text: Input text to analyze
intent_context: The detected intent to help with disambiguation
Returns:
List of extracted entities with confidence scores
"""
start_time = time.perf_counter()
entities = []
text_lower = text.lower()
# 1. Fast lightweight extraction first
lightweight_entities = self.lightweight_extractor.extract(text)
for entity_value, entity_type in lightweight_entities:
entities.append(ExtractedEntity(
entity_type=entity_type.lower(),
value=entity_value,
confidence=0.8, # High confidence for regex matches
start_pos=text.find(entity_value),
end_pos=text.find(entity_value) + len(entity_value),
context=text[max(0, text.find(entity_value)-10):text.find(entity_value)+len(entity_value)+10]
))
# 2. Advanced pattern matching for domain-specific entities
entities.extend(self._extract_person_names(text, text_lower, intent_context))
entities.extend(self._extract_grade_levels(text, text_lower))
entities.extend(self._extract_subjects(text, text_lower))
entities.extend(self._extract_dates(text, text_lower))
entities.extend(self._extract_contact_info(text, text_lower))
entities.extend(self._extract_school_terms(text, text_lower))
entities.extend(self._extract_ages(text, text_lower))
entities.extend(self._extract_staff_roles(text, text_lower))
# 3. Smart NLTK extraction with conditional usage (only if lightweight didn't find enough)
if len(entities) < 2 and self._should_use_nltk(text, entities):
nltk_entities = self._extract_entities_with_nltk_cached(text)
entities.extend(nltk_entities)
# Update performance stats
self._performance_stats['total_queries'] += 1
# Extract entity relationships
relationship_entities = self._extract_entity_relationships(text, entities)
entities.extend(relationship_entities)
# Context-aware entity extraction
context_entities = self._extract_context_entities(text, entities, intent_context)
entities.extend(context_entities)
# Sort by confidence and remove overlaps
entities = self._resolve_entity_conflicts(entities)
# Detect relationships between entities
entities = self._detect_entity_relationships(entities, text)
logger.info(f"🔍 Rule-based extracted {len(entities)} entities from: '{text[:50]}...'")
for entity in entities:
logger.info(f" 📍 {entity.entity_type}: '{entity.value}' (confidence: {entity.confidence:.2f})")
return entities
def _should_use_nltk(self, text: str, existing_entities: List[ExtractedEntity]) -> bool:
"""Determine if NLTK extraction should be used"""
# Skip NLTK if text is very short
words = text.split()
if len(words) < 5:
return False
# Skip NLTK if we already have good entities
if len(existing_entities) >= 3:
return False
# Skip NLTK if no potential entities detected
if not self._has_potential_entities(text):
return False
# Use NLTK for complex queries with potential entities
return len(words) > 10 or any(trigger.search(text) for trigger in self._compiled_triggers)
def _has_potential_entities(self, text: str) -> bool:
"""Check if text has potential entities without using NLTK"""
# Check for capitalized words (potential proper nouns)
words = text.split()
capitalized_words = [word for word in words if word[0].isupper() and len(word) > 2]
if len(capitalized_words) < 2:
return False
# Check for name patterns
for pattern in self._compiled_patterns:
if pattern.search(text):
return True
# Check for location indicators
location_indicators = ['in', 'at', 'from', 'to', 'visit', 'go', 'located']
if any(indicator in text.lower() for indicator in location_indicators):
return True
# Check for organization indicators
org_indicators = ['corporation', 'company', 'organization', 'school', 'university', 'inc', 'ltd']
if any(indicator in text.lower() for indicator in org_indicators):
return True
return True
def _extract_entities_with_nltk_cached(self, text: str) -> List[ExtractedEntity]:
"""Cached NLTK entity extraction with lazy loading"""
# Check in-memory cache first
cache_key = text.lower().strip()
if cache_key in self._nltk_cache:
cached_result, timestamp = self._nltk_cache[cache_key]
if time.time() - timestamp < self._cache_timeout:
self._performance_stats['cache_hits'] += 1
return cached_result
# Lazy load NLTK if not already loaded
if not self.nltk_loaded:
self._load_nltk()
# Extract with NLTK
entities = self._extract_entities_with_nltk(text)
# Cache result
self._nltk_cache[cache_key] = (entities, time.time())
self._performance_stats['nltk_queries'] += 1
return entities
def _load_nltk(self):
"""Lazy load NLTK models only when needed"""
try:
import nltk
from nltk import word_tokenize, pos_tag, ne_chunk, Tree
# Download required NLTK data if not present
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt', quiet=True)
try:
nltk.data.find('taggers/averaged_perceptron_tagger')
except LookupError:
nltk.download('averaged_perceptron_tagger', quiet=True)
try:
nltk.data.find('chunkers/maxent_ne_chunker')
except LookupError:
nltk.download('maxent_ne_chunker', quiet=True)
self.nltk_loaded = True
logger.info("✅ NLTK models loaded successfully")
except Exception as e:
logger.warning(f"⚠️ Failed to load NLTK: {e}")
self.nltk_loaded = False
def _extract_entities_with_nltk(self, text: str) -> List[ExtractedEntity]:
"""Enhanced entity extraction using NLTK"""
entities = []
try:
import nltk
from nltk import word_tokenize, pos_tag, ne_chunk, Tree
# Tokenize and tag the text
tokens = word_tokenize(text)
pos_tags = pos_tag(tokens)
# Extract named entities using NLTK
tree = ne_chunk(pos_tags)
for subtree in tree:
if isinstance(subtree, Tree):
entity_text = ' '.join([token for token, pos in subtree.leaves()])
entity_label = subtree.label()
# Map NLTK entity types to our types
if entity_label == 'PERSON':
entities.append(ExtractedEntity(
entity_type='person_name',
value=entity_text,
confidence=0.8,
start_pos=text.find(entity_text),
end_pos=text.find(entity_text) + len(entity_text)
))
elif entity_label in ['GPE', 'LOCATION']:
entities.append(ExtractedEntity(
entity_type='location',
value=entity_text,
confidence=0.7,
start_pos=text.find(entity_text),
end_pos=text.find(entity_text) + len(entity_text)
))
elif entity_label == 'ORGANIZATION':
entities.append(ExtractedEntity(
entity_type='organization',
value=entity_text,
confidence=0.7,
start_pos=text.find(entity_text),
end_pos=text.find(entity_text) + len(entity_text)
))
# Extract proper nouns using POS tagging
for token, pos in pos_tags:
if pos == 'NNP' and len(token) > 2: # Proper noun, at least 3 characters
if token.istitle() and self._is_valid_name(token):
entities.append(ExtractedEntity(
entity_type='person_name',
value=token,
confidence=0.6,
start_pos=text.find(token),
end_pos=text.find(token) + len(token)
))
logger.info(f"🔍 NLTK extracted {len(entities)} entities")
except Exception as e:
logger.warning(f"NLTK entity extraction failed: {e}")
return entities
def get_performance_stats(self) -> Dict:
"""Get performance statistics"""
stats = self._performance_stats.copy()
if stats['total_queries'] > 0:
stats['nltk_usage_rate'] = stats['nltk_queries'] / stats['total_queries']
stats['cache_hit_rate'] = stats['cache_hits'] / stats['total_queries']
else:
stats['nltk_usage_rate'] = 0
stats['cache_hit_rate'] = 0
stats['cache_size'] = len(self._nltk_cache)
stats['nltk_loaded'] = self.nltk_loaded
return stats
def clear_cache(self):
"""Clear all caches"""
self._nltk_cache.clear()
print("🗑️ NLTK cache cleared")
def force_nltk(self, text: str) -> List[ExtractedEntity]:
"""Force NLTK extraction for testing"""
entities = []
if self._should_use_nltk(text, entities):
nltk_entities = self._extract_entities_with_nltk_cached(text)
entities.extend(nltk_entities)
return entities
def skip_nltk(self, text: str) -> List[ExtractedEntity]:
"""Skip NLTK extraction for testing"""
# Temporarily disable NLTK
original_loaded = self.nltk_loaded
self.nltk_loaded = False
# Extract without NLTK
entities = self.extract_entities(text)
# Restore original state
self.nltk_loaded = original_loaded
return entities
async def extract_entities_async(self, text: str, intent_context: str = None) -> List[ExtractedEntity]:
"""
Async version of extract_entities for better performance with NLP models
"""
entities = []
# Use rule-based extraction for domain-specific entities
text_lower = text.lower()
# Extract different entity types using pattern matching
entities.extend(self._extract_person_names(text, text_lower, intent_context))
entities.extend(self._extract_grade_levels(text, text_lower))
entities.extend(self._extract_subjects(text, text_lower))
entities.extend(self._extract_dates(text, text_lower))
entities.extend(self._extract_contact_info(text, text_lower))
entities.extend(self._extract_school_terms(text, text_lower))
entities.extend(self._extract_ages(text, text_lower))
entities.extend(self._extract_staff_roles(text, text_lower))
# Sort by confidence and remove overlaps
entities = self._resolve_entity_conflicts(entities)
logger.info(f"🔍 Total extracted {len(entities)} entities from: '{text[:50]}...'")
for entity in entities:
logger.info(f" 📍 {entity.entity_type}: '{entity.value}' (confidence: {entity.confidence:.2f})")
return entities
def _build_grade_patterns(self) -> Dict[str, List[str]]:
"""Build patterns for grade level detection"""
return {
"numeric": [
r"grade\s*(\d+)", r"(\d+)(?:st|nd|rd|th)?\s*grade",
r"level\s*(\d+)", r"year\s*(\d+)"
],
"written": [
r"(kindergarten|kinder|prep)", r"(first|second|third|fourth|fifth|sixth)\s*grade",
r"grade\s*(one|two|three|four|five|six|seven|eight|nine|ten)"
],
"filipino": [
r"(unang|ikalawang|ikatlong|ikatatlong|ikaapat|ikalimang|ikaanim)\s*baitang",
r"baitang\s*(isa|dalawa|tatlo|apat|lima|anim)",
r"(unang|ikalawang|ikatlong|ikatatlong|ikaapat|ikalimang|ikaanim)\s*grade",
r"grade\s*(isa|dalawa|tatlo|apat|lima|anim)",
r"para\s+sa\s+(ikatlong|ikatatlong|ikalimang|unang|ikalawang|ikaapat|ikaanim)\s+baitang"
]
}
def _build_subject_patterns(self) -> List[str]:
"""Build patterns for subject/curriculum detection"""
return [
# Core subjects
"mathematics", "math", "matematika", "science", "agham", "english", "ingles",
"filipino", "reading", "writing", "social studies", "araling panlipunan",
"physical education", "pe", "music", "art", "computer", "technology",
# Elementary specific
"mother tongue", "mother tongue based multilingual education", "mtb-mle",
"values education", "edukasyong pagpapakatao", "health", "nutrition",
# Skills and activities
"spelling", "composition", "grammar", "arithmetic", "geometry",
"science experiments", "sports", "drawing", "singing"
]
def _build_name_patterns(self) -> List[str]:
"""Build patterns for name extraction"""
return [
# English patterns - handle both uppercase and lowercase names
r"my name is ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"i['\s]*m ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"i am ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"hi[,\s]*i['\s]*m ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"hi[,\s]+i am ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"hello[,\s]*i['\s]*m ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"hello[,\s]+i am ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$|\s+who|\s+but)",
r"call me ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$)",
r"this is ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$)",
# Child/family patterns - handle both uppercase and lowercase names
r"my (?:son|daughter|child) (?:is\s+)?([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+who|\s+and|\s*,|\s*$)",
r"(?:son|daughter|child) named ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+who|\s+and|\s*,|\s*$)",
r"her name is ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$)",
r"his name is ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+and|\s*,|\s*$)",
r"daughter ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+who|\s+and|\s*,|\s*$)",
# Filipino patterns - handle both uppercase and lowercase names
r"ako si ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+at|\s*,|\s*$)",
r"anak ko si ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+at|\s*,|\s*$)",
r"pangalan (?:niya|niya) ay ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+at|\s*,|\s*$)",
# Aklanon patterns - handle both uppercase and lowercase names
r"ngaean ko si ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+at|\s*,|\s*$)",
r"ngaean ko ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+at|\s*,|\s*$)",
r"ngaean si ([A-Za-z]+(?:\s+[A-Za-z]+)*?)(?:\s+at|\s*,|\s*$)"
]
def _build_date_patterns(self) -> List[str]:
"""Build patterns for date/time extraction"""
return [
# Enrollment dates
r"(\d{1,2}\/\d{1,2}\/\d{4})", r"(\d{1,2}-\d{1,2}-\d{4})",
r"(january|february|march|april|may|june|july|august|september|october|november|december)\s+(\d{1,2})",
r"(\d{1,2})\s+(january|february|march|april|may|june|july|august|september|october|november|december)",
# Filipino months
r"(enero|pebrero|marso|abril|mayo|hunyo|hulyo|agosto|setyembre|oktubre|nobyembre|disyembre)\s+(\d{1,2})",
# Relative dates
r"(next week|next month|tomorrow|today|yesterday)",
r"(sa susunod na linggo|bukas|ngayon|kahapon)"
]
def _build_contact_patterns(self) -> List[str]:
"""Build patterns for contact information"""
return [
# Phone numbers
r"(\+63\d{10})", r"(09\d{9})", r"(\d{3}-\d{3}-\d{4})",
r"(\d{4}-\d{3}-\d{4})", r"(\(\d{3}\)\s*\d{3}-\d{4})",
# Email addresses
r"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})"
]
def _build_school_terminology(self) -> List[str]:
"""Build school-specific terminology patterns"""
return [
# School facilities
"library", "cafeteria", "gym", "gymnasium", "playground", "computer lab",
"science lab", "clinic", "principal's office", "teacher's lounge",
# School activities
"enrollment", "registration", "orientation", "graduation", "field trip",
"parent-teacher conference", "school fair", "sports day",
# Academic terms
"semester", "quarter", "grading period", "report card", "transcript",
"curriculum", "lesson plan", "homework", "assignment", "project"
]
def _extract_person_names(self, text: str, text_lower: str, intent_context: str = None) -> List[ExtractedEntity]:
"""Extract person names with context awareness and intent-based filtering"""
entities = []
# 🚨 CRITICAL FIX: Skip name extraction for location/facilities inquiries
# These intents often contain question words that shouldn't be names
if intent_context in ['location_inquiry', 'facilities_inquiry']:
# Check if this looks like a question (contains question words)
question_indicators = ['diin', 'saan', 'where', 'what', 'how', 'when', 'why', 'which']
if any(indicator in text_lower for indicator in question_indicators):
logger.info(f"🔍 Skipping name extraction for {intent_context} with question indicators")
return entities
for pattern in self.name_patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
name = match.group(1).strip()
# Clean the name (remove common prefixes)
name = self._clean_extracted_name(name)
# Validate name (exclude common false positives)
if self._is_valid_name(name):
# Determine name type based on context
name_type = self._classify_name_type(text_lower, name.lower())
entity = ExtractedEntity(
entity_type=name_type,
value=name.title(),
confidence=self._calculate_name_confidence(name, text_lower),
start_pos=match.start(1),
end_pos=match.end(1),
context=text[max(0, match.start()-20):match.end()+20]
)
entities.append(entity)
return entities
def _extract_grade_levels(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract grade level information"""
entities = []
# Numeric grades
for pattern in self.grade_patterns["numeric"]:
matches = re.finditer(pattern, text_lower)
for match in matches:
grade_num = match.group(1)
if grade_num.isdigit() and 1 <= int(grade_num) <= 12:
entity = ExtractedEntity(
entity_type="grade_level",
value=f"Grade {grade_num}",
confidence=0.9,
start_pos=match.start(),
end_pos=match.end(),
context=text[max(0, match.start()-15):match.end()+15]
)
entities.append(entity)
# Written grades (kindergarten, first grade, etc.)
for pattern in self.grade_patterns["written"]:
matches = re.finditer(pattern, text_lower)
for match in matches:
grade_text = match.group(1)
normalized_grade = self._normalize_grade_level(grade_text)
if normalized_grade:
entity = ExtractedEntity(
entity_type="grade_level",
value=normalized_grade,
confidence=0.85,
start_pos=match.start(),
end_pos=match.end(),
context=text[max(0, match.start()-15):match.end()+15]
)
entities.append(entity)
# Filipino grades (ikalimang baitang, etc.)
for pattern in self.grade_patterns["filipino"]:
matches = re.finditer(pattern, text_lower)
for match in matches:
grade_text = match.group(1)
normalized_grade = self._normalize_filipino_grade(grade_text)
if normalized_grade:
entity = ExtractedEntity(
entity_type="grade_level",
value=normalized_grade,
confidence=0.9,
start_pos=match.start(),
end_pos=match.end(),
context=text[max(0, match.start()-15):match.end()+15]
)
entities.append(entity)
return entities
def _extract_subjects(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract academic subjects using word boundary matching with validation"""
entities = []
for subject in self.subject_patterns:
# Use word boundary matching to avoid false positives
import re
pattern = r'\b' + re.escape(subject) + r'\b'
matches = re.finditer(pattern, text_lower)
for match in matches:
start_pos = match.start()
# Skip false positives for "pe" - only match if it's standalone or part of "physical education"
if subject == "pe":
# Check if it's part of "person" - if so, skip this match
if start_pos + 2 < len(text_lower) and text_lower[start_pos:start_pos+6] == "person":
continue # Skip this match as it's "person" not "PE"
# Additional validation to prevent false positives
if self._validate_subject_extraction(subject, text, start_pos, match.end()):
entity = ExtractedEntity(
entity_type="academic_subject",
value=subject.title(),
confidence=0.8,
start_pos=start_pos,
end_pos=match.end(),
context=text[max(0, start_pos-15):match.end()+15]
)
entities.append(entity)
return entities
def _validate_subject_extraction(self, subject: str, text: str, start_pos: int, end_pos: int) -> bool:
"""Validate that subject extraction makes sense in context"""
# Get surrounding context
context_start = max(0, start_pos - 10)
context_end = min(len(text), end_pos + 10)
context = text[context_start:context_end].lower()
# Known problematic patterns
problematic_patterns = {
'art': [
# Prevent "art" from being extracted from "start"
r'start', r'starts', r'starting',
# Prevent from other common words
r'part', r'parts', r'party', r'parties',
r'smart', r'chart', r'dart', r'heart'
],
'math': [
# Prevent from common words
r'match', r'matches', r'matching',
r'path', r'paths', r'paths'
],
'science': [
# Prevent from common words
r'since', r'conscience'
],
'pe': [
# Prevent from person-related words
r'person', r'people', r'personal'
]
}
if subject in problematic_patterns:
for pattern in problematic_patterns[subject]:
if re.search(pattern, context):
return False
# Additional context validation
# If subject appears in a time-related context, be more careful
time_contexts = ['time', 'when', 'start', 'end', 'begin', 'finish']
if any(time_word in context for time_word in time_contexts):
# For academic subjects, require class/subject context
class_contexts = ['class', 'subject', 'course', 'lesson', 'period']
if not any(class_word in context for class_word in class_contexts):
return False
return True
def _extract_dates(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract date and time information"""
entities = []
for pattern in self.date_patterns:
matches = re.finditer(pattern, text_lower)
for match in matches:
date_text = match.group(0)
parsed_date = self._parse_date(date_text)
if parsed_date:
entity = ExtractedEntity(
entity_type="date",
value=parsed_date,
confidence=0.85,
start_pos=match.start(),
end_pos=match.end(),
context=text[max(0, match.start()-15):match.end()+15]
)
entities.append(entity)
return entities
def _extract_contact_info(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract contact information"""
entities = []
for pattern in self.contact_patterns:
matches = re.finditer(pattern, text)
for match in matches:
contact_value = match.group(1)
contact_type = "phone_number" if any(c.isdigit() for c in contact_value) else "email"
entity = ExtractedEntity(
entity_type=contact_type,
value=contact_value,
confidence=0.95,
start_pos=match.start(1),
end_pos=match.end(1),
context=text[max(0, match.start()-10):match.end()+10]
)
entities.append(entity)
return entities
def _extract_school_terms(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract school-specific terminology"""
entities = []
for term in self.school_terms:
if term in text_lower:
start_pos = text_lower.find(term)
entity = ExtractedEntity(
entity_type="school_term",
value=term.title(),
confidence=0.7,
start_pos=start_pos,
end_pos=start_pos + len(term),
context=text[max(0, start_pos-15):start_pos+len(term)+15]
)
entities.append(entity)
return entities
def _extract_ages(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract age information"""
entities = []
age_patterns = [
r"(\d+)\s*years?\s*old", r"age\s*(\d+)", r"(\d+)\s*(?:y/o|yo)",
r"(\d+)\s*taon", r"edad\s*(\d+)"
]
for pattern in age_patterns:
matches = re.finditer(pattern, text_lower)
for match in matches:
age = match.group(1)
if age.isdigit() and 3 <= int(age) <= 18: # Reasonable age range for students
entity = ExtractedEntity(
entity_type="age",
value=f"{age} years old",
confidence=0.9,
start_pos=match.start(),
end_pos=match.end(),
context=text[max(0, match.start()-15):match.end()+15]
)
entities.append(entity)
return entities
def _extract_staff_roles(self, text: str, text_lower: str) -> List[ExtractedEntity]:
"""Extract staff roles and administrative positions"""
entities = []
# Staff role patterns with English and Filipino terms
staff_role_patterns = {
"principal": {
"patterns": [
r"(?:school\s+)?(?:head|principal|director)",
r"(?:head\s+)?(?:principal|headmaster|headmistress)",
r"(?:school\s+)?(?:administrator|administration)",
r"punong\s+(?:guro|teacher|ng\s+paaralan)(?:\s|$)",
r"(?:head\s+)?(?:ng\s+paaralan|sa\s+paaralan)",
r"(?:principal|direktor|administrador)",
r"in\s+charge(?:\s+of)?",
r"(?:who\s+)?(?:runs|manages)\s+(?:the\s+)?school"
],
"confidence": 0.95
},
"teacher": {
"patterns": [
r"(?:class\s+)?(?:teacher|instructor|educator)",
r"(?:guro|maestro|maestra)(?!\s+(?:ng\s+paaralan|sa\s+paaralan|ng\s+eskwela))",
r"(?:grade\s+\d+\s+)?teacher",
r"(?:subject\s+)?teacher",
r"sino\s+ang\s+(?:guro|teacher)",
r"(?:adviser|advisor)",
r"(?:homeroom\s+)?teacher",
r"guro\s+(?:para\s+sa|ng|sa)\s+(?:ikatlong|ikalimang|unang|ikalawang|ikaapat|ikaanim)\s+baitang"
],
"confidence": 0.90
},
"guidance": {
"patterns": [
r"(?:guidance\s+)?(?:counselor|counsellor)",
r"guidance\s+(?:office|teacher)",
r"school\s+psychologist"
],
"confidence": 0.85
},
"nurse": {
"patterns": [
r"(?:school\s+)?nurse",
r"clinic\s+(?:staff|nurse)",
r"health\s+(?:officer|personnel)"
],
"confidence": 0.85
},
"secretary": {
"patterns": [
r"(?:school\s+)?(?:secretary|clerk)",
r"(?:administrative\s+)?(?:assistant|staff)",
r"office\s+(?:staff|personnel)"
],
"confidence": 0.80
}
}
for role_type, role_info in staff_role_patterns.items():
for pattern in role_info["patterns"]:
matches = re.finditer(pattern, text_lower)
for match in matches:
entity = ExtractedEntity(
entity_type="staff_role",
value=role_type,
confidence=role_info["confidence"],
start_pos=match.start(),
end_pos=match.end(),
context=text[max(0, match.start()-10):match.end()+10]
)
entities.append(entity)
return entities
def _clean_extracted_name(self, name: str) -> str: