Spaces:
Sleeping
Sleeping
File size: 58,752 Bytes
ac07929 f2841cf ac07929 f2841cf ac07929 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 | """
Intelligent Query Processing System for Inyandiko Legal AI Assistant
query analysis, intent detection, and response optimization
"""
import re
import json
import logging
import asyncio
from typing import Dict, List, Optional, Tuple, Any, Union, Set
from dataclasses import dataclass, asdict, field
from enum import Enum
from datetime import datetime, timedelta
import numpy as np
from collections import defaultdict
from collections import Counter as CollectionsCounter
import pickle
import hashlib
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, PorterStemmer
from nltk.tag import pos_tag
from nltk.chunk import ne_chunk
from nltk.tree import Tree
import spacy
from textblob import TextBlob
try:
import langdetect
from langdetect import detect, DetectorFactory
except ImportError:
langdetect = None
detect = None
DetectorFactory = None
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import KMeans, DBSCAN
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import itertools
import joblib
import torch
import torch.nn as nn
from transformers import (
AutoTokenizer,
AutoModel,
AutoModelForSequenceClassification,
pipeline,
BertTokenizer,
BertModel,
)
import sentence_transformers
from sentence_transformers import SentenceTransformer
import librosa
import soundfile as sf
from scipy import signal
import webrtcvad
import aiofiles
import asyncio
from concurrent.futures import ThreadPoolExecutor
import multiprocessing as mp
from prometheus_client import Counter, Histogram, Gauge
from production_components import ProductionModelOrchestrator
import time
import structlog
logger = structlog.get_logger(__name__)
if DetectorFactory:
DetectorFactory.seed = 0
try:
nlp_en = spacy.load("en_core_web_sm")
except OSError:
nlp_en = None
try:
nlp_rw = spacy.load("rw_core_news_sm")
except OSError:
nlp_rw = None
lemmatizer = WordNetLemmatizer()
stemmer = PorterStemmer()
query_processing_counter = Counter(
"queries_processed_total",
"Total queries processed",
["intent", "language", "complexity"],
)
query_processing_duration = Histogram(
"query_processing_duration_seconds", "Query processing duration"
)
intent_confidence_gauge = Gauge(
"intent_confidence_score", "Intent detection confidence score"
)
class QueryLanguage(Enum):
"""Supported query languages"""
KINYARWANDA = "rw"
ENGLISH = "en"
FRENCH = "fr"
SWAHILI = "sw"
UNKNOWN = "unknown"
class QueryIntent(Enum):
"""Legal query intent categories"""
LEGAL_ADVICE = "legal_advice"
LEGAL_INFORMATION = "legal_information"
DOCUMENT_SEARCH = "document_search"
CASE_LAW = "case_law"
STATUTE_LOOKUP = "statute_lookup"
PROCEDURE_INQUIRY = "procedure_inquiry"
RIGHTS_INQUIRY = "rights_inquiry"
OBLIGATION_INQUIRY = "obligation_inquiry"
PENALTY_INQUIRY = "penalty_inquiry"
COURT_PROCESS = "court_process"
CONTRACT_RELATED = "contract_related"
PROPERTY_LAW = "property_law"
FAMILY_LAW = "family_law"
CRIMINAL_LAW = "criminal_law"
CIVIL_LAW = "civil_law"
COMMERCIAL_LAW = "commercial_law"
LABOR_LAW = "labor_law"
TAX_LAW = "tax_law"
CONSTITUTIONAL_LAW = "constitutional_law"
ADMINISTRATIVE_LAW = "administrative_law"
GENERAL_INQUIRY = "general_inquiry"
GREETING = "greeting"
CLARIFICATION = "clarification"
COMPLAINT = "complaint"
UNKNOWN = "unknown"
class QueryComplexity(Enum):
"""Query complexity levels"""
SIMPLE = "simple"
MODERATE = "moderate"
COMPLEX = "complex"
VERY_COMPLEX = "very_complex"
class EmotionalTone(Enum):
"""Emotional tone of the query"""
NEUTRAL = "neutral"
URGENT = "urgent"
FRUSTRATED = "frustrated"
CONFUSED = "confused"
ANXIOUS = "anxious"
ANGRY = "angry"
GRATEFUL = "grateful"
FORMAL = "formal"
INFORMAL = "informal"
@dataclass
class LegalEntity:
"""Legal entity extracted from query"""
text: str
entity_type: str
start_pos: int
end_pos: int
confidence: float
context: Optional[str] = None
@dataclass
class QueryKeyword:
"""Important keyword with metadata"""
word: str
lemma: str
pos_tag: str
importance_score: float
legal_relevance: float
frequency: int
@dataclass
class QueryContext:
"""Context information for the query"""
previous_queries: List[str]
session_id: str
user_id: Optional[str]
conversation_history: List[Dict]
domain_context: Optional[str]
geographic_context: Optional[str]
@dataclass
class ProcessedQuery:
"""Comprehensive processed query with all analysis"""
original_query: str
cleaned_query: str
language: QueryLanguage
intent: QueryIntent
intent_confidence: float
complexity: QueryComplexity
emotional_tone: EmotionalTone
keywords: List[QueryKeyword]
entities: List[LegalEntity]
legal_concepts: List[str]
question_type: str
urgency_level: int
requires_disclaimer: bool
suggested_followup: List[str]
processing_time: float
expanded_queries: List[str] = field(default_factory=list)
context: Optional[QueryContext] = None
embedding: Optional[np.ndarray] = None
metadata: Optional[Dict[str, Any]] = None
class KinyarwandaProcessor:
"""Specialized processor for Kinyarwanda language queries"""
def __init__(self):
self.legal_terms_mapping = {
"urukiko": "court",
"ubucamanza": "justice",
"umucamanza": "judge",
"ubunyangamugayo": "prosecutor",
"umwunganira": "lawyer",
"umwunganira mukuru": "attorney",
"amategeko": "law",
"itegeko": "law/statute",
"amasezerano": "contract",
"ubwiyunge": "rights",
"inshingano": "obligations",
"igihano": "penalty",
"icyaha": "crime",
"urubanza": "case",
"ubukwe": "marriage",
"gutandukana": "divorce",
"abana": "children",
"umuryango": "family",
"umurage": "inheritance",
"umutungo": "property",
"ubutaka": "land",
"inzu": "house",
"ubwite": "ownership",
"ubujura": "theft",
"ubwicanyi": "murder",
"gufata ku ngufu": "rape",
"kwica": "killing",
"guhemuka": "corruption",
"kwicuza": "to sue",
"gusaba": "to request",
"kwemeza": "to confirm",
"guhakana": "to deny",
"kwemera": "to accept",
}
self.question_patterns = {
r"\b(ni|ari)\s+iki\b": "what_is",
r"\b(ni|ari)\s+nde\b": "who_is",
r"\b(ni|ari)\s+he\b": "where_is",
r"\b(ni|ari)\s+ryari\b": "when_is",
r"\bngombwa\s+gute\b": "how_to",
r"\bese\s+.*\?": "yes_no_question",
r"\bmbese\s+.*\?": "confirmation_question",
r"\bnshaka\s+kumenya\b": "want_to_know",
r"\bmfite\s+ikibazo\b": "have_problem",
}
self.urgency_indicators = {
"byihutirwa": 5,
"vuba": 4,
"nonaha": 4,
"mbere": 3,
"byihuse": 4,
"ntidushobora gutegereza": 5,
}
def translate_legal_terms(self, text: str) -> str:
"""Translate Kinyarwanda legal terms to English for better processing"""
translated_text = text.lower()
for kinyarwanda_term, english_term in self.legal_terms_mapping.items():
pattern = r"\b" + re.escape(kinyarwanda_term) + r"\b"
translated_text = re.sub(pattern, english_term, translated_text)
return translated_text
def detect_question_type(self, text: str) -> str:
"""Detect question type in Kinyarwanda"""
text_lower = text.lower()
for pattern, question_type in self.question_patterns.items():
if re.search(pattern, text_lower):
return question_type
return "general_question"
def assess_urgency(self, text: str) -> int:
"""Assess urgency level from Kinyarwanda text"""
text_lower = text.lower()
max_urgency = 1
for indicator, urgency_level in self.urgency_indicators.items():
if indicator in text_lower:
max_urgency = max(max_urgency, urgency_level)
return max_urgency
class LegalConceptExtractor:
"""Extract legal concepts and classify legal domains"""
def __init__(self):
self.legal_domains = {
"criminal_law": [
"crime",
"criminal",
"murder",
"theft",
"assault",
"fraud",
"robbery",
"burglary",
"rape",
"domestic violence",
"drug",
"trafficking",
"money laundering",
"corruption",
"bribery",
"embezzlement",
],
"civil_law": [
"contract",
"tort",
"negligence",
"damages",
"liability",
"breach",
"compensation",
"civil suit",
"personal injury",
"defamation",
],
"family_law": [
"marriage",
"divorce",
"custody",
"child support",
"alimony",
"adoption",
"domestic relations",
"paternity",
"guardianship",
],
"property_law": [
"property",
"real estate",
"land",
"ownership",
"title",
"deed",
"mortgage",
"lease",
"rent",
"landlord",
"tenant",
"eviction",
],
"commercial_law": [
"business",
"company",
"corporation",
"partnership",
"commercial",
"trade",
"commerce",
"intellectual property",
"trademark",
"patent",
],
"labor_law": [
"employment",
"worker",
"employee",
"employer",
"workplace",
"salary",
"wage",
"termination",
"discrimination",
"harassment",
],
"constitutional_law": [
"constitution",
"constitutional",
"rights",
"freedom",
"liberty",
"due process",
"equal protection",
"government",
"state",
],
"administrative_law": [
"government agency",
"regulation",
"administrative",
"permit",
"license",
"public administration",
"bureaucracy",
],
"tax_law": [
"tax",
"taxation",
"revenue",
"income tax",
"vat",
"customs",
"tax evasion",
"tax return",
"deduction",
],
}
self.legal_procedures = [
"court",
"judge",
"lawyer",
"attorney",
"legal advice",
"lawsuit",
"litigation",
"trial",
"hearing",
"appeal",
"verdict",
"judgment",
"settlement",
"mediation",
"arbitration",
"legal process",
]
self.rights_keywords = [
"right",
"rights",
"entitled",
"entitlement",
"privilege",
"freedom",
"liberty",
"protection",
"guarantee",
"constitutional right",
]
self.obligations_keywords = [
"obligation",
"duty",
"responsibility",
"liable",
"must",
"required",
"mandatory",
"compulsory",
"binding",
"legal duty",
]
def extract_legal_concepts(self, text: str) -> List[str]:
"""Extract legal concepts from text"""
text_lower = text.lower()
concepts = []
for domain, keywords in self.legal_domains.items():
for keyword in keywords:
if keyword in text_lower:
concepts.append(f"{domain}:{keyword}")
for procedure in self.legal_procedures:
if procedure in text_lower:
concepts.append(f"procedure:{procedure}")
for right_keyword in self.rights_keywords:
if right_keyword in text_lower:
concepts.append(f"rights:{right_keyword}")
for obligation_keyword in self.obligations_keywords:
if obligation_keyword in text_lower:
concepts.append(f"obligations:{obligation_keyword}")
return list(set(concepts))
def classify_legal_domain(self, text: str) -> Tuple[str, float]:
"""Classify the primary legal domain of the query"""
text_lower = text.lower()
domain_scores = defaultdict(int)
for domain, keywords in self.legal_domains.items():
for keyword in keywords:
if keyword in text_lower:
weight = len(keyword.split())
domain_scores[domain] += weight
if not domain_scores:
return "general", 0.0
top_domain = max(domain_scores.items(), key=lambda x: x[1])
total_score = sum(domain_scores.values())
confidence = top_domain[1] / total_score if total_score > 0 else 0.0
return top_domain[0], confidence
class IntentClassifier:
"""intent classification using multiple approaches"""
def __init__(self):
self.vectorizer = TfidfVectorizer(max_features=5000, ngram_range=(1, 3))
self.classifier: Optional[LogisticRegression] = None
self.label_encoder = LabelEncoder()
self.is_trained = False
self.intent_patterns = {
QueryIntent.LEGAL_ADVICE: [
r"\b(what should i do|advice|recommend|suggest)\b",
r"\b(help me|guide me|assist me)\b",
r"\b(best course of action|next step)\b",
],
QueryIntent.LEGAL_INFORMATION: [
r"\b(what is|define|explain|meaning of)\b",
r"\b(information about|details about|tell me about)\b",
r"\b(how does.*work|what does.*mean)\b",
],
QueryIntent.DOCUMENT_SEARCH: [
r"\b(find document|search for|locate|document about)\b",
r"\b(where can i find|show me|need document)\b",
],
QueryIntent.STATUTE_LOOKUP: [
r"\b(law about|statute|regulation|legal provision)\b",
r"\b(what does the law say|according to law)\b",
],
QueryIntent.PROCEDURE_INQUIRY: [
r"\b(how to|procedure|process|steps to)\b",
r"\b(what is the process|how do i)\b",
],
QueryIntent.RIGHTS_INQUIRY: [
r"\b(my rights|what rights|am i entitled)\b",
r"\b(rights in|legal rights|constitutional rights)\b",
],
QueryIntent.PENALTY_INQUIRY: [
r"\b(penalty|punishment|fine|sentence)\b",
r"\b(what happens if|consequences of)\b",
],
QueryIntent.GREETING: [
r"\b(hello|hi|good morning|good afternoon|greetings)\b",
r"\b(muraho|mwaramutse|mwiriwe)\b",
],
}
def _extract_features(self, text: str) -> Dict[str, Any]:
"""Extract features for intent classification"""
features = {}
features["word_count"] = len(text.split())
features["char_count"] = len(text)
features["question_marks"] = text.count("?")
features["exclamation_marks"] = text.count("!")
question_words = ["what", "how", "when", "where", "why", "who", "which"]
features["has_question_word"] = any(
word in text.lower() for word in question_words
)
legal_keywords = [
"law",
"legal",
"court",
"judge",
"lawyer",
"right",
"obligation",
]
features["legal_keyword_count"] = sum(
1 for word in legal_keywords if word in text.lower()
)
urgency_words = ["urgent", "emergency", "immediately", "asap", "quickly"]
features["urgency_score"] = sum(
1 for word in urgency_words if word in text.lower()
)
return features
def classify_intent_rule_based(self, text: str) -> Tuple[QueryIntent, float]:
"""Rule-based intent classification"""
text_lower = text.lower()
intent_scores = defaultdict(int)
for intent, patterns in self.intent_patterns.items():
for pattern in patterns:
matches = len(re.findall(pattern, text_lower))
intent_scores[intent] += matches
if not intent_scores:
return QueryIntent.UNKNOWN, 0.0
top_intent = max(intent_scores.items(), key=lambda x: x[1])
total_score = sum(intent_scores.values())
confidence = top_intent[1] / total_score if total_score > 0 else 0.0
return top_intent[0], confidence
def classify_intent_ml(self, text: str) -> Tuple[QueryIntent, float]:
"""Machine learning-based intent classification"""
if not self.is_trained or self.classifier is None:
return QueryIntent.UNKNOWN, 0.0
try:
text_vector = self.vectorizer.transform([text])
prediction = self.classifier.predict(text_vector)[0]
probabilities = self.classifier.predict_proba(text_vector)[0]
confidence = max(probabilities)
intent_label = self.label_encoder.inverse_transform([prediction])[0]
intent = QueryIntent(intent_label)
return intent, confidence
except Exception:
return QueryIntent.UNKNOWN, 0.0
def train_classifier(self, training_data: List[Tuple[str, str]]):
"""Train the ML classifier with labeled data"""
if len(training_data) < 10:
return False
texts, labels = zip(*training_data)
encoded_labels = self.label_encoder.fit_transform(labels)
text_vectors = self.vectorizer.fit_transform(texts)
self.classifier = LogisticRegression(random_state=42, max_iter=1000)
self.classifier.fit(text_vectors, encoded_labels)
self.is_trained = True
return True
class EmotionAnalyzer:
"""Analyze emotional tone and sentiment of queries"""
def __init__(self):
self.emotion_keywords = {
EmotionalTone.URGENT: [
"urgent",
"emergency",
"immediately",
"asap",
"quickly",
"hurry",
"byihutirwa",
"vuba",
"nonaha",
],
EmotionalTone.FRUSTRATED: [
"frustrated",
"annoyed",
"fed up",
"tired of",
"sick of",
"ndashaje",
"naramaze",
],
EmotionalTone.CONFUSED: [
"confused",
"don't understand",
"unclear",
"puzzled",
"ntabwo nkumva",
"sibyumva",
],
EmotionalTone.ANXIOUS: [
"worried",
"concerned",
"anxious",
"nervous",
"afraid",
"mfite ubwoba",
"ndagira impungenge",
],
EmotionalTone.ANGRY: [
"angry",
"mad",
"furious",
"furious",
"outraged",
"livid",
"narakaye",
"mbaruye",
],
EmotionalTone.GRATEFUL: [
"thank",
"grateful",
"appreciate",
"thanks",
"murakoze",
"ndabashimiye",
],
}
def analyze_emotion(self, text: str) -> Tuple[EmotionalTone, float]:
"""Analyze emotional tone of the text"""
text_lower = text.lower()
emotion_scores = defaultdict(int)
for emotion, keywords in self.emotion_keywords.items():
for keyword in keywords:
if keyword in text_lower:
emotion_scores[emotion] += 1
try:
blob = TextBlob(text)
sentiment_polarity = blob.sentiment.polarity # type: ignore
if sentiment_polarity < -0.5:
emotion_scores[EmotionalTone.ANGRY] += 2
elif sentiment_polarity < -0.2:
emotion_scores[EmotionalTone.FRUSTRATED] += 1
elif sentiment_polarity > 0.5:
emotion_scores[EmotionalTone.GRATEFUL] += 1
except Exception:
pass
formal_indicators = ["please", "kindly", "would you", "could you", "may i"]
informal_indicators = ["hey", "hi", "what's up", "gonna", "wanna"]
formal_count = sum(
1 for indicator in formal_indicators if indicator in text_lower
)
informal_count = sum(
1 for indicator in informal_indicators if indicator in text_lower
)
if formal_count > informal_count:
emotion_scores[EmotionalTone.FORMAL] += formal_count
elif informal_count > 0:
emotion_scores[EmotionalTone.INFORMAL] += informal_count
if not emotion_scores:
return EmotionalTone.NEUTRAL, 1.0
top_emotion = max(emotion_scores.items(), key=lambda x: x[1])
total_score = sum(emotion_scores.values())
confidence = top_emotion[1] / total_score if total_score > 0 else 0.0
return top_emotion[0], confidence
class QueryComplexityAnalyzer:
"""Analyze query complexity and determine processing requirements"""
def __init__(self):
self.complexity_factors = {
"word_count": {
"simple": (1, 10),
"moderate": (11, 25),
"complex": (26, 50),
"very_complex": (51, float("inf")),
},
"legal_concepts": {
"simple": (0, 1),
"moderate": (2, 3),
"complex": (4, 6),
"very_complex": (7, float("inf")),
},
"question_count": {
"simple": (1, 1),
"moderate": (2, 2),
"complex": (3, 4),
"very_complex": (5, float("inf")),
},
"entity_count": {
"simple": (0, 2),
"moderate": (3, 5),
"complex": (6, 10),
"very_complex": (11, float("inf")),
},
}
def analyze_complexity(
self, text: str, legal_concepts: List[str], entities: List[LegalEntity]
) -> Tuple[QueryComplexity, Dict[str, Any]]:
"""Analyze query complexity"""
word_count = len(text.split())
legal_concept_count = len(legal_concepts)
question_count = text.count("?") + len(
re.findall(r"\b(what|how|when|where|why|who|which)\b", text.lower())
)
entity_count = len(entities)
metrics = {
"word_count": word_count,
"legal_concepts": legal_concept_count,
"question_count": max(question_count, 1),
"entity_count": entity_count,
}
complexity_scores = defaultdict(int)
for factor, value in metrics.items():
for complexity_level, (min_val, max_val) in self.complexity_factors[
factor
].items():
if min_val <= value <= max_val:
complexity_scores[complexity_level] += 1
break
if complexity_scores["very_complex"] >= 2:
complexity = QueryComplexity.VERY_COMPLEX
elif complexity_scores["complex"] >= 2:
complexity = QueryComplexity.COMPLEX
elif complexity_scores["moderate"] >= 2:
complexity = QueryComplexity.MODERATE
else:
complexity = QueryComplexity.SIMPLE
analysis_details = {
"metrics": metrics,
"complexity_scores": dict(complexity_scores),
"primary_factors": [
factor for factor, score in complexity_scores.items() if score > 0
],
}
return complexity, analysis_details
class QueryProcessor:
"""Main intelligent query processing system"""
def __init__(
self,
model_orchestrator: ProductionModelOrchestrator,
config: Dict[str, Any] = {},
):
self.config = config or {}
self.kinyarwanda_processor = KinyarwandaProcessor()
self.legal_concept_extractor = LegalConceptExtractor()
self.intent_classifier = IntentClassifier()
self.emotion_analyzer = EmotionAnalyzer()
self.complexity_analyzer = QueryComplexityAnalyzer()
self.model_orchestrator = model_orchestrator
self.sentence_model: Optional[SentenceTransformer] = None
self.thread_pool = ThreadPoolExecutor(max_workers=4)
self.conversation_contexts = {}
self.context_timeout = timedelta(hours=2)
async def initialize(self) -> None:
"""Initialize the query processor and load necessary resources"""
logger.info("Initializing IntelligentQueryProcessor...")
try:
# Load SentenceTransformer model
loop = asyncio.get_running_loop()
if self.sentence_model is None:
self.sentence_model = await loop.run_in_executor(
self.thread_pool,
SentenceTransformer,
"all-MiniLM-L6-v2"
)
logger.info("Loaded SentenceTransformer model.")
# Verify spaCy models
if nlp_en is None:
logger.warning("English spaCy model not loaded.")
if nlp_rw is None:
logger.warning("Kinyarwanda spaCy model not loaded.")
self.is_initialized = True
logger.info("IntelligentQueryProcessor initialized successfully.")
except Exception as e:
logger.error(f"Failed to initialize IntelligentQueryProcessor: {str(e)}")
self.is_initialized = False
raise
def _detect_language(self, text: str) -> QueryLanguage:
"""Detect the language of the query"""
try:
if len(text.strip()) < 3:
return QueryLanguage.UNKNOWN
if detect is not None:
detected_lang = detect(text)
lang_mapping = {
"rw": QueryLanguage.KINYARWANDA,
"en": QueryLanguage.ENGLISH,
"fr": QueryLanguage.FRENCH,
"sw": QueryLanguage.SWAHILI,
}
return lang_mapping.get(detected_lang, QueryLanguage.UNKNOWN)
else:
raise Exception("langdetect not available")
except Exception:
kinyarwanda_indicators = [
"amategeko",
"urukiko",
"ubucamanza",
"umwunganira",
"murakoze",
]
text_lower = text.lower()
if any(indicator in text_lower for indicator in kinyarwanda_indicators):
return QueryLanguage.KINYARWANDA
return QueryLanguage.ENGLISH
def _clean_query(self, text: str) -> str:
"""Clean and normalize the query text"""
text = re.sub(r"\s+", " ", text.strip())
text = re.sub(r"\s+([.!?])", r"\1", text)
text = re.sub(r"([.!?])\s*([A-Z])", r"\1 \2", text)
text = re.sub(r"[.!?]{2,}", ".", text)
return text
def _extract_entities(
self, text: str, language: QueryLanguage
) -> List[LegalEntity]:
"""Extract legal entities from text"""
entities = []
nlp_model = nlp_rw if language == QueryLanguage.KINYARWANDA else nlp_en
if nlp_model:
try:
doc = nlp_model(text)
for ent in doc.ents:
entity = LegalEntity(
text=ent.text,
entity_type=ent.label_,
start_pos=ent.start_char,
end_pos=ent.end_char,
confidence=1.0,
)
entities.append(entity)
except Exception:
pass
if not entities:
try:
tokens = word_tokenize(text)
nltk_pos_tags = pos_tag(tokens)
chunks = ne_chunk(nltk_pos_tags)
for chunk in chunks:
if isinstance(chunk, Tree):
entity_text = " ".join([token for token, pos in chunk.leaves()])
entity = LegalEntity(
text=entity_text,
entity_type=chunk.label(),
start_pos=text.find(entity_text),
end_pos=text.find(entity_text) + len(entity_text),
confidence=0.8,
)
entities.append(entity)
except Exception:
pass
return entities
def _extract_keywords(
self, text: str, language: QueryLanguage
) -> List[QueryKeyword]:
"""Extract important keywords from the query"""
keywords = []
tokens = word_tokenize(text.lower())
if language == QueryLanguage.ENGLISH:
stop_words = set(stopwords.words("english"))
else:
stop_words = set()
stop_words.update(
[
"the",
"a",
"an",
"and",
"or",
"but",
"in",
"on",
"at",
"to",
"for",
"of",
"with",
"by",
]
)
filtered_tokens = [
token
for token in tokens
if token.isalpha() and token not in stop_words and len(token) > 2
]
pos_tags: List[Tuple[str, str]] = []
try:
pos_tags = pos_tag(filtered_tokens)
except Exception:
pos_tags = [(token, "NN") for token in filtered_tokens]
word_freq = CollectionsCounter(filtered_tokens)
for token, tag in pos_tags:
importance_score = word_freq.get(token, 0)
if tag.startswith("NN"):
importance_score *= 1.5
elif tag.startswith("VB"):
importance_score *= 1.2
legal_terms = [
"law",
"legal",
"court",
"judge",
"right",
"contract",
"crime",
"civil",
]
legal_relevance = 1.0
if any(legal_term in token for legal_term in legal_terms):
legal_relevance = 2.0
keyword = QueryKeyword(
word=token,
lemma=lemmatizer.lemmatize(
token,
pos="n",
),
pos_tag=tag,
importance_score=importance_score,
legal_relevance=legal_relevance,
frequency=word_freq.get(token, 0),
)
keywords.append(keyword)
keywords.sort(
key=lambda x: x.importance_score * x.legal_relevance, reverse=True
)
return keywords[:20]
async def _resolve_query_with_context(
self, query: str, history: List[Dict[str, str]]
) -> str:
"""
Rewrites the current query to be a standalone question using conversation history.
"""
if not history:
return query
formatted_history = "\n".join(
[
f"User: {turn['user']}\nAssistant: {turn['assistant']}"
for turn in history
]
)
prompt = f"""<s>[INST] You are an expert in understanding conversation flow. Your task is to rewrite the "CURRENT QUERY" into a standalone, complete question. Use the "CONVERSATION HISTORY" to resolve pronouns and context.
If the "CURRENT QUERY" is already a complete question, simply return it unchanged.
CONVERSATION HISTORY:
---
{formatted_history}
---
CURRENT QUERY: {query}
Standalone Question: [/INST]"""
try:
# This is a critical, fast task. Use a short timeout and token limit.
rewritten_query = await asyncio.wait_for(
self.model_orchestrator.generate_raw(prompt, max_new_tokens=75),
timeout=3.0,
)
logger.info(
f"Contextual query rewrite. Original: '{query}', Rewritten: '{rewritten_query}'"
)
return rewritten_query
except asyncio.TimeoutError:
logger.warning("Contextual query rewrite timed out. Using original query.")
return query
except Exception as e:
logger.error(f"Error during query rewrite: {e}. Using original query.")
return query
def _expand_query(
self, keywords: List[QueryKeyword], entities: List[LegalEntity]
) -> List[str]:
"""Generates expanded queries from keywords and entities."""
if not keywords:
return []
# Get top 3 keywords and top 2 entities
top_keywords = [kw.word for kw in keywords[:3]]
top_entities = [ent.text for ent in entities[:2]]
# Combine them into a single list of important terms, avoiding duplicates
core_terms = list(dict.fromkeys(top_keywords + top_entities))
if not core_terms:
return []
expanded_queries = set()
# Simple combinations
if len(core_terms) > 1:
expanded_queries.add(" ".join(core_terms))
expanded_queries.add(" ".join(reversed(core_terms)))
# Question-style queries
expanded_queries.add(f"what is the law regarding {' and '.join(core_terms)}")
expanded_queries.add(f"details about {' and '.join(core_terms)}")
# Permutations of top keywords
if len(top_keywords) > 1:
for p in itertools.permutations(top_keywords):
expanded_queries.add(" ".join(p))
if len(expanded_queries) >= 5: # Limit permutations
break
# Remove the original keyword order if it exists to avoid redundancy
original_combo = " ".join(top_keywords)
if original_combo in expanded_queries and len(expanded_queries) > 1:
expanded_queries.remove(original_combo)
return list(expanded_queries)[:4] # Return up to 4 expanded queries
def _determine_question_type(self, text: str, language: QueryLanguage) -> str:
"""Determine the type of question being asked"""
text_lower = text.lower()
if language == QueryLanguage.ENGLISH:
if re.search(
r"\bwhat\s+(is|are|was|were|will|would|can|could|should|do|does|did)\b",
text_lower,
):
return "what_question"
elif re.search(
r"\bhow\s+(to|do|does|did|can|could|should|will|would|much|many)\b",
text_lower,
):
return "how_question"
elif re.search(
r"\bwhen\s+(is|are|was|were|will|would|can|could|should|do|does|did)\b",
text_lower,
):
return "when_question"
elif re.search(
r"\bwhere\s+(is|are|was|were|will|would|can|could|should|do|does|did)\b",
text_lower,
):
return "where_question"
elif re.search(
r"\bwhy\s+(is|are|was|were|will|would|can|could|should|do|does|did)\b",
text_lower,
):
return "why_question"
elif re.search(
r"\bwho\s+(is|are|was|were|will|would|can|could|should|do|does|did)\b",
text_lower,
):
return "who_question"
elif re.search(
r"\b(can|could|should|will|would|may|might)\s+i\b", text_lower
):
return "permission_question"
elif re.search(r"\b(is|are|was|were|will|would)\s+.*\?", text_lower):
return "yes_no_question"
elif language == QueryLanguage.KINYARWANDA:
return self.kinyarwanda_processor.detect_question_type(text)
if "?" in text:
return "general_question"
else:
return "statement"
def _assess_urgency(
self, text: str, language: QueryLanguage, emotional_tone: EmotionalTone
) -> int:
"""Assess the urgency level of the query (1-5 scale)"""
urgency_level = 1
if emotional_tone == EmotionalTone.URGENT:
urgency_level = 5
elif emotional_tone == EmotionalTone.ANXIOUS:
urgency_level = 4
elif emotional_tone == EmotionalTone.FRUSTRATED:
urgency_level = 3
if language == QueryLanguage.KINYARWANDA:
kinyarwanda_urgency = self.kinyarwanda_processor.assess_urgency(text)
urgency_level = max(urgency_level, kinyarwanda_urgency)
urgency_keywords = {
"emergency": 5,
"urgent": 5,
"immediately": 4,
"asap": 4,
"quickly": 3,
"soon": 2,
"help": 3,
"problem": 2,
}
text_lower = text.lower()
for keyword, level in urgency_keywords.items():
if keyword in text_lower:
urgency_level = max(urgency_level, level)
return min(urgency_level, 5)
def _requires_disclaimer(
self, intent: QueryIntent, complexity: QueryComplexity
) -> bool:
"""Determine if the response requires a legal disclaimer"""
if intent == QueryIntent.LEGAL_ADVICE:
return True
if complexity in [QueryComplexity.COMPLEX, QueryComplexity.VERY_COMPLEX]:
advice_related_intents = [
QueryIntent.PROCEDURE_INQUIRY,
QueryIntent.RIGHTS_INQUIRY,
QueryIntent.PENALTY_INQUIRY,
QueryIntent.COURT_PROCESS,
]
if intent in advice_related_intents:
return True
return False
def _generate_followup_suggestions(
self, intent: QueryIntent, legal_concepts: List[str]
) -> List[str]:
"""Generate suggested follow-up questions"""
suggestions = []
if intent == QueryIntent.LEGAL_INFORMATION:
suggestions.extend(
[
"Would you like to know about related legal procedures?",
"Do you need information about your rights in this matter?",
"Are you looking for specific legal documents?",
]
)
elif intent == QueryIntent.PROCEDURE_INQUIRY:
suggestions.extend(
[
"What documents do you need for this procedure?",
"How long does this process typically take?",
"What are the costs involved?",
]
)
elif intent == QueryIntent.RIGHTS_INQUIRY:
suggestions.extend(
[
"What are your obligations in this situation?",
"How can you enforce these rights?",
"What happens if these rights are violated?",
]
)
for concept in legal_concepts[:3]:
if "criminal_law" in concept:
suggestions.append("Do you need information about criminal procedures?")
elif "family_law" in concept:
suggestions.append(
"Would you like to know about family court procedures?"
)
elif "property_law" in concept:
suggestions.append(
"Do you need information about property registration?"
)
return suggestions[:5]
async def _create_embedding(self, text: str) -> Optional[np.ndarray]:
"""Create semantic embedding for the query"""
if self.sentence_model is None:
return None
try:
loop = asyncio.get_running_loop()
embedding = await loop.run_in_executor(
self.thread_pool,
self.sentence_model.encode,
text
)
if isinstance(embedding, torch.Tensor):
embedding = embedding.detach().cpu().numpy()
elif isinstance(embedding, list):
embedding = np.array(embedding)
return embedding
except Exception as e:
logger.error("Failed to create embedding", error=str(e), exc_info=True)
return None
def _perform_sync_analysis(
self, cleaned_query: str, resolved_query: str, detected_language: QueryLanguage
) -> Dict[str, Any]:
"""
Synchronous helper to run all CPU-bound analysis tasks off the event loop.
"""
# Use Kinyarwanda processor if needed for translation before analysis
analysis_query = (
self.kinyarwanda_processor.translate_legal_terms(cleaned_query)
if detected_language == QueryLanguage.KINYARWANDA
else cleaned_query
)
entities = self._extract_entities(analysis_query, detected_language)
keywords = self._extract_keywords(analysis_query, detected_language)
legal_concepts = self.legal_concept_extractor.extract_legal_concepts(
analysis_query
)
# Hybrid intent classification
intent_rule, conf_rule = self.intent_classifier.classify_intent_rule_based(analysis_query)
intent_ml, conf_ml = self.intent_classifier.classify_intent_ml(analysis_query)
intent, intent_confidence = (intent_ml, conf_ml) if conf_ml > conf_rule else (intent_rule, conf_rule)
emotional_tone, _ = self.emotion_analyzer.analyze_emotion(resolved_query)
complexity, complexity_details = self.complexity_analyzer.analyze_complexity(
cleaned_query, legal_concepts, entities
)
question_type = self._determine_question_type(cleaned_query, detected_language)
urgency_level = self._assess_urgency(
cleaned_query, detected_language, emotional_tone
)
requires_disclaimer = self._requires_disclaimer(intent, complexity)
expanded_queries = self._expand_query(keywords, entities)
return {
"language": detected_language,
"intent": intent,
"intent_confidence": intent_confidence,
"complexity": complexity,
"emotional_tone": emotional_tone,
"keywords": keywords,
"entities": entities,
"legal_concepts": legal_concepts,
"question_type": question_type,
"urgency_level": urgency_level,
"requires_disclaimer": requires_disclaimer,
"expanded_queries": expanded_queries,
"metadata": {"complexity_details": complexity_details}
}
async def comprehensive_analyze(
self,
query: str,
language: str, # This is a hint, but we still detect
session_id: str,
conversation_history: Optional[List[Dict[str, str]]] = None,
) -> ProcessedQuery:
"""
The main public method for comprehensive query analysis with context.
This version is non-blocking and consolidates all analysis logic.
"""
start_time = time.time()
# 1. Resolve query based on context
history = conversation_history or []
resolved_query = await self._resolve_query_with_context(query, history)
try:
# 2. Perform basic, fast operations on the event loop
cleaned_query = self._clean_query(resolved_query)
detected_language = self._detect_language(cleaned_query)
# 3. Run CPU-bound analysis and embedding creation concurrently
loop = asyncio.get_running_loop()
analysis_task = loop.run_in_executor(
self.thread_pool,
self._perform_sync_analysis,
cleaned_query,
resolved_query,
detected_language,
)
embedding_task = self._create_embedding(cleaned_query)
analysis_results, embedding = await asyncio.gather(
analysis_task, embedding_task
)
processing_time = time.time() - start_time
# 4. Assemble the final ProcessedQuery object
return ProcessedQuery(
original_query=query,
cleaned_query=cleaned_query,
suggested_followup=[], # Placeholder
processing_time=processing_time,
embedding=embedding,
context=QueryContext(
previous_queries=[t["user"] for t in history],
session_id=session_id,
user_id=None,
conversation_history=history,
domain_context=None,
geographic_context=None,
),
**analysis_results,
)
except Exception as e:
logger.error(f"Error during query analysis pipeline: {e}", exc_info=True)
return ProcessedQuery(
original_query=query,
cleaned_query=query,
language=QueryLanguage.UNKNOWN,
intent=QueryIntent.UNKNOWN,
intent_confidence=0.0,
complexity=QueryComplexity.SIMPLE,
emotional_tone=EmotionalTone.NEUTRAL,
keywords=[],
entities=[],
legal_concepts=[],
question_type="unknown",
urgency_level=1,
requires_disclaimer=True,
suggested_followup=[],
processing_time=time.time() - start_time,
expanded_queries=[],
embedding=None,
)
async def process_query(
self, query: str, context: Optional[QueryContext] = None, use_cache: bool = True
) -> ProcessedQuery:
"""
DEPRECATED: This method is superseded by `comprehensive_analyze`.
It is kept for backward compatibility but should not be used for new development.
"""
logger.warning("The 'process_query' method is deprecated. Use 'comprehensive_analyze' instead.")
start_time = time.time()
try:
cleaned_query = self._clean_query(query)
language = self._detect_language(cleaned_query)
if language == QueryLanguage.KINYARWANDA:
translated_query = self.kinyarwanda_processor.translate_legal_terms(
cleaned_query
)
else:
translated_query = cleaned_query
entities = self._extract_entities(translated_query, language)
keywords = self._extract_keywords(translated_query, language)
legal_concepts = self.legal_concept_extractor.extract_legal_concepts(
translated_query
)
intent_rule, confidence_rule = (
self.intent_classifier.classify_intent_rule_based(translated_query)
)
intent_ml, confidence_ml = self.intent_classifier.classify_intent_ml(
translated_query
)
if confidence_ml > confidence_rule:
intent, intent_confidence = intent_ml, confidence_ml
else:
intent, intent_confidence = intent_rule, confidence_rule
emotional_tone, emotion_confidence = self.emotion_analyzer.analyze_emotion(
cleaned_query
)
complexity, complexity_details = (
self.complexity_analyzer.analyze_complexity(
cleaned_query, legal_concepts, entities
)
)
question_type = self._determine_question_type(cleaned_query, language)
urgency_level = self._assess_urgency(
cleaned_query, language, emotional_tone
)
requires_disclaimer = self._requires_disclaimer(intent, complexity)
suggested_followup = self._generate_followup_suggestions(
intent, legal_concepts
)
embedding = await self._create_embedding(cleaned_query)
expanded_queries = self._expand_query(keywords, entities)
processing_time = time.time() - start_time
processed_query = ProcessedQuery(
original_query=query,
cleaned_query=cleaned_query,
language=language,
intent=intent,
intent_confidence=intent_confidence,
complexity=complexity,
emotional_tone=emotional_tone,
keywords=keywords,
entities=entities,
legal_concepts=legal_concepts,
question_type=question_type,
urgency_level=urgency_level,
requires_disclaimer=requires_disclaimer,
suggested_followup=suggested_followup,
processing_time=processing_time,
expanded_queries=expanded_queries,
context=context,
embedding=await embedding if asyncio.iscoroutine(embedding) else embedding,
metadata={
"complexity_details": complexity_details,
"emotion_confidence": emotion_confidence,
"translated_query": (
translated_query
if language == QueryLanguage.KINYARWANDA
else None
),
},
)
query_processing_counter.labels(
intent=intent.value,
language=language.value,
complexity=complexity.value,
).inc()
query_processing_duration.observe(processing_time)
intent_confidence_gauge.set(intent_confidence)
return processed_query
except Exception as e:
processing_time = time.time() - start_time
error_query = ProcessedQuery(
original_query=query,
cleaned_query=query,
language=QueryLanguage.UNKNOWN,
intent=QueryIntent.UNKNOWN,
intent_confidence=0.0,
complexity=QueryComplexity.SIMPLE,
emotional_tone=EmotionalTone.NEUTRAL,
keywords=[],
entities=[],
legal_concepts=[],
question_type="unknown",
urgency_level=1,
requires_disclaimer=True,
suggested_followup=[],
processing_time=processing_time,
context=context,
metadata={"error": str(e)},
)
query_processing_counter.labels(
intent="error", language="error", complexity="error"
).inc()
return error_query
async def batch_process_queries(self, queries: List[str]) -> List[ProcessedQuery]:
"""Process multiple queries concurrently"""
tasks = [self.process_query(query) for query in queries]
results = await asyncio.gather(*tasks, return_exceptions=True)
processed_queries = []
for i, result in enumerate(results):
if isinstance(result, Exception):
error_query = ProcessedQuery(
original_query=queries[i],
cleaned_query=queries[i],
language=QueryLanguage.UNKNOWN,
intent=QueryIntent.UNKNOWN,
intent_confidence=0.0,
complexity=QueryComplexity.SIMPLE,
emotional_tone=EmotionalTone.NEUTRAL,
keywords=[],
entities=[],
legal_concepts=[],
question_type="unknown",
urgency_level=1,
requires_disclaimer=True,
suggested_followup=[],
processing_time=0.0,
metadata={"error": str(result)},
)
processed_queries.append(error_query)
else:
processed_queries.append(result)
return processed_queries
def update_conversation_context(self, session_id: str, query: ProcessedQuery):
"""Update conversation context for a session"""
if session_id not in self.conversation_contexts:
self.conversation_contexts[session_id] = {
"queries": [],
"last_updated": datetime.now(),
"session_id": session_id,
}
context = self.conversation_contexts[session_id]
context["queries"].append(
{
"query": query.original_query,
"intent": query.intent.value,
"timestamp": datetime.now(),
"legal_concepts": query.legal_concepts,
}
)
context["last_updated"] = datetime.now()
if len(context["queries"]) > 10:
context["queries"] = context["queries"][-10:]
def get_conversation_context(self, session_id: str) -> Optional[QueryContext]:
"""Get conversation context for a session"""
if session_id not in self.conversation_contexts:
return None
context_data = self.conversation_contexts[session_id]
if datetime.now() - context_data["last_updated"] > self.context_timeout:
del self.conversation_contexts[session_id]
return None
return QueryContext(
previous_queries=[q["query"] for q in context_data["queries"]],
session_id=session_id,
user_id=None,
conversation_history=context_data["queries"],
domain_context=None,
geographic_context="Rwanda",
)
def get_processing_stats(self) -> Dict[str, Any]:
"""Get processing statistics"""
return {
"cache_size": 0, # Caching is now external
"cache_limit": 0,
"active_conversations": len(self.conversation_contexts),
"supported_languages": [lang.value for lang in QueryLanguage],
"supported_intents": [intent.value for intent in QueryIntent],
"is_ml_trained": self.intent_classifier.is_trained,
}
def clear_cache(self):
"""Clear query cache"""
logger.warning("QueryProcessor.clear_cache() is deprecated. Use CacheManager.")
def cleanup_old_contexts(self):
"""Clean up old conversation contexts"""
current_time = datetime.now()
expired_sessions = [
session_id
for session_id, context in self.conversation_contexts.items()
if current_time - context["last_updated"] > self.context_timeout
]
for session_id in expired_sessions:
del self.conversation_contexts[session_id]
async def cleanup(self):
"""Cleanup resources"""
self.thread_pool.shutdown(wait=True)
self.conversation_contexts.clear()
async def health_check(self) -> bool:
"""Check health of query processor components"""
try:
if self.sentence_model is None:
logger.warning("SentenceTransformer model not loaded.")
return False
if nlp_en is None:
logger.warning("English spaCy model not loaded.")
return False
if nlp_rw is None:
logger.warning("Kinyarwanda spaCy model not loaded.")
if not self.intent_classifier.is_trained:
logger.warning("Intent classifier not trained.")
try:
test_query = "This is a test query."
processed = await self.process_query(test_query, use_cache=False)
if processed.intent == QueryIntent.UNKNOWN:
logger.warning("Test query processing failed.")
return False
except Exception:
return False
logger.info("Query processor health check passed.")
return True
except Exception:
return False
|