davidtran999 commited on
Commit
2f1e37b
·
verified ·
1 Parent(s): f1cd3b5

Upload backend/chatbot/chatbot.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/chatbot/chatbot.py +882 -0
backend/chatbot/chatbot.py ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chatbot with ML-based intent classification for natural language queries.
3
+ """
4
+ import json
5
+ import re
6
+ import unicodedata
7
+ from pathlib import Path
8
+ from typing import Dict, List, Tuple, Any, Optional
9
+ import joblib
10
+ from sklearn.feature_extraction.text import TfidfVectorizer
11
+ from sklearn.naive_bayes import MultinomialNB
12
+ from sklearn.pipeline import Pipeline
13
+ import numpy as np
14
+ from hue_portal.core.models import Procedure, Fine, Office, Advisory
15
+ from hue_portal.core.search_ml import search_with_ml, expand_query_with_synonyms
16
+
17
+
18
+ def format_fine_amount(min_fine: Optional[float], max_fine: Optional[float]) -> Optional[str]:
19
+ """
20
+ Format fine amount as '200.000 - 400.000 VNĐ'.
21
+
22
+ Args:
23
+ min_fine: Minimum fine amount.
24
+ max_fine: Maximum fine amount.
25
+
26
+ Returns:
27
+ Formatted string or None if both are None.
28
+ """
29
+ if min_fine is not None and max_fine is not None:
30
+ # Format with thousand separators (dots for Vietnamese format)
31
+ min_str = f"{min_fine:,.0f}".replace(",", ".")
32
+ max_str = f"{max_fine:,.0f}".replace(",", ".")
33
+ return f"{min_str} - {max_str} VNĐ"
34
+ elif min_fine is not None:
35
+ min_str = f"{min_fine:,.0f}".replace(",", ".")
36
+ return f"{min_str} VNĐ"
37
+ return None
38
+
39
+
40
+ # Training data for intent classification (fallback when chưa có model huấn luyện)
41
+ INTENT_TRAINING_DATA = {
42
+ "search_fine": [
43
+ "mức phạt", "phạt bao nhiêu", "tiền phạt", "vi phạm giao thông",
44
+ "vượt đèn đỏ", "nồng độ cồn", "không đội mũ bảo hiểm",
45
+ "mức phạt là gì", "phạt như thế nào", "hành vi vi phạm",
46
+ "điều luật", "nghị định", "mức xử phạt"
47
+ ],
48
+ "search_procedure": [
49
+ "thủ tục", "làm thủ tục", "hồ sơ", "điều kiện",
50
+ "thủ tục cư trú", "thủ tục ANTT", "thủ tục PCCC",
51
+ "cần giấy tờ gì", "làm như thế nào", "quy trình",
52
+ "thời hạn", "lệ phí", "nơi nộp"
53
+ ],
54
+ "search_office": [
55
+ "địa chỉ", "điểm tiếp dân", "công an", "phòng ban",
56
+ "số điện thoại", "giờ làm việc", "nơi tiếp nhận",
57
+ "đơn vị nào", "ở đâu", "liên hệ"
58
+ ],
59
+ "search_advisory": [
60
+ "cảnh báo", "lừa đảo", "scam", "thủ đoạn",
61
+ "cảnh giác", "an toàn", "bảo mật",
62
+ "cảnh báo lừa đảo giả danh công an",
63
+ "mạo danh cán bộ công an",
64
+ "lừa đảo mạo danh",
65
+ "cảnh báo an ninh",
66
+ "thủ đoạn lừa đảo",
67
+ "scam giả danh",
68
+ "cảnh giác lừa đảo online",
69
+ "lừa đảo qua điện thoại",
70
+ "cảnh báo bảo mật",
71
+ "mạo danh cán bộ",
72
+ "lừa đảo giả danh",
73
+ "cảnh báo lừa đảo",
74
+ "thủ đoạn scam",
75
+ "cảnh giác an toàn",
76
+ "lừa đảo online",
77
+ "cảnh báo mạo danh"
78
+ ],
79
+ "search_legal": [
80
+ "quyết định", "quy định", "thông tư", "nghị quyết",
81
+ "văn bản pháp luật", "văn bản quy phạm", "điều lệnh",
82
+ "kỷ luật đảng viên", "kỷ luật", "xử lý kỷ luật",
83
+ "quyết định 69", "quyết định 264", "qd 69", "qd 264",
84
+ "thông tư 02", "tt 02", "điều lệnh cand",
85
+ "quy định kỷ luật", "hình thức kỷ luật", "mức kỷ luật",
86
+ "xử lý vi phạm", "kỷ luật đảng", "kỷ luật cán bộ",
87
+ "quy định về", "theo quyết định", "theo thông tư",
88
+ "nội dung quyết định", "nội dung thông tư", "điều khoản"
89
+ ],
90
+ "general_query": [
91
+ "xin chào", "giúp tôi", "tư vấn", "hỏi",
92
+ "thông tin", "tra cứu", "tìm kiếm"
93
+ ]
94
+ }
95
+
96
+ # Đường dẫn artefact model
97
+ TRAINING_DIR = Path(__file__).resolve().parent / "training"
98
+ ARTIFACT_MODEL = TRAINING_DIR / "artifacts" / "intent_model.joblib"
99
+ ARTIFACT_METRICS = TRAINING_DIR / "artifacts" / "metrics.json"
100
+
101
+ # Legal-related keywords reused across intent calibration
102
+ LEGAL_KEYWORDS = [
103
+ "quyết định",
104
+ "quy định",
105
+ "thông tư",
106
+ "nghị quyết",
107
+ "văn bản pháp luật",
108
+ "văn bản quy phạm",
109
+ "điều lệnh",
110
+ "kỷ luật đảng viên",
111
+ "kỷ luật",
112
+ "xử lý kỷ luật",
113
+ "hình thức kỷ luật",
114
+ "mức kỷ luật",
115
+ "quyết định 69",
116
+ "quyết định 264",
117
+ "qd 69",
118
+ "qd 264",
119
+ "thông tư 02",
120
+ "tt 02",
121
+ ]
122
+
123
+ # Response templates
124
+ RESPONSE_TEMPLATES = {
125
+ "search_fine": "Tôi tìm thấy {count} mức phạt liên quan đến '{query}':",
126
+ "search_procedure": "Tôi tìm thấy {count} thủ tục liên quan đến '{query}':",
127
+ "search_office": "Tôi tìm thấy {count} đơn vị liên quan đến '{query}':",
128
+ "search_advisory": "Tôi tìm thấy {count} cảnh báo liên quan đến '{query}':",
129
+ "general_query": "Tôi có thể giúp bạn tra cứu thông tin về thủ tục, mức phạt, đơn vị hoặc cảnh báo. Bạn muốn tìm gì?",
130
+ "no_results": "Xin lỗi, tôi không tìm thấy thông tin liên quan đến '{query}'. Vui lòng thử lại với từ khóa khác.",
131
+ "greeting": "Xin chào! Tôi có thể giúp bạn tra cứu các thông tin liên quan về các văn bản quy định pháp luật về xử lý kỷ luật cán bộ, đảng viên.",
132
+ }
133
+
134
+
135
+ class Chatbot:
136
+ def __init__(self):
137
+ self.intent_classifier = None
138
+ self.intent_metrics: Optional[Dict[str, Any]] = None
139
+ self._load_classifier()
140
+
141
+ def _load_classifier(self):
142
+ """Load pretrained classifier nếu có, fallback tự huấn luyện seed data."""
143
+ if ARTIFACT_MODEL.exists():
144
+ try:
145
+ self.intent_classifier = joblib.load(ARTIFACT_MODEL)
146
+ if ARTIFACT_METRICS.exists():
147
+ self.intent_metrics = json.loads(ARTIFACT_METRICS.read_text(encoding="utf-8"))
148
+ return
149
+ except Exception as exc:
150
+ print(f"Warning: không thể load intent_model.joblib ({exc}). Sẽ huấn luyện tạm thời.")
151
+ self.intent_classifier = None
152
+ self.intent_metrics = None
153
+ self._train_classifier()
154
+
155
+ def _train_classifier(self):
156
+ """Train intent classification model."""
157
+ try:
158
+ # Prepare training data
159
+ texts = []
160
+ labels = []
161
+
162
+ for intent, examples in INTENT_TRAINING_DATA.items():
163
+ for example in examples:
164
+ texts.append(self._preprocess_text(example))
165
+ labels.append(intent)
166
+
167
+ if not texts:
168
+ return
169
+
170
+ # Create and train pipeline
171
+ self.intent_classifier = Pipeline([
172
+ ('tfidf', TfidfVectorizer(
173
+ analyzer='word',
174
+ ngram_range=(1, 2),
175
+ min_df=1,
176
+ lowercase=True,
177
+ token_pattern=r'\b\w+\b'
178
+ )),
179
+ ('clf', MultinomialNB())
180
+ ])
181
+
182
+ self.intent_classifier.fit(texts, labels)
183
+ except Exception as e:
184
+ print(f"Error training classifier: {e}")
185
+ self.intent_classifier = None
186
+
187
+ def _preprocess_text(self, text: str) -> str:
188
+ """Preprocess text for classification - keep Vietnamese characters."""
189
+ if not text:
190
+ return ""
191
+ text = text.lower().strip()
192
+ # Only remove punctuation marks, keep all letters (including Vietnamese) and numbers
193
+ # Remove: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
194
+ text = re.sub(r'[!"#$%&\'()*+,\-./:;<=>?@\[\\\]^_`{|}~]', ' ', text)
195
+ text = re.sub(r'\s+', ' ', text)
196
+ return text.strip()
197
+
198
+ def _remove_accents(self, text: str) -> str:
199
+ """Remove diacritics for accent-insensitive matching."""
200
+ if not text:
201
+ return ""
202
+ normalized = unicodedata.normalize("NFD", text)
203
+ return "".join(ch for ch in normalized if unicodedata.category(ch) != "Mn")
204
+
205
+ def _keyword_in(self, query_lower: str, query_ascii: str, keyword: str) -> bool:
206
+ """Check keyword presence in either original or accent-free text."""
207
+ kw_lower = keyword.lower()
208
+ if kw_lower in query_lower:
209
+ return True
210
+ kw_ascii = self._remove_accents(kw_lower)
211
+ return kw_ascii in query_ascii
212
+
213
+ def classify_intent(self, query: str, context: Optional[Dict[str, Any]] = None) -> Tuple[str, float]:
214
+ """
215
+ Classify user intent from query with optional context.
216
+
217
+ Args:
218
+ query: User query string.
219
+ context: Optional context dictionary with recent_messages, entities, etc.
220
+
221
+ Returns:
222
+ Tuple of (intent, confidence_score)
223
+ """
224
+ # Use context to improve classification if available
225
+ if context:
226
+ # Check recent intents in context
227
+ recent_messages = context.get("recent_messages", [])
228
+ if recent_messages:
229
+ # Get most recent intent
230
+ for msg in reversed(recent_messages):
231
+ if msg.get("intent") and msg.get("intent") != "greeting":
232
+ recent_intent = msg.get("intent")
233
+ # Boost confidence if query is short and recent intent is relevant
234
+ if len(query.split()) <= 5:
235
+ # Likely a follow-up question
236
+ return (recent_intent, 0.85)
237
+
238
+ model_intent, model_confidence = self._model_based_intent(query)
239
+ keyword_intent, keyword_confidence = self._keyword_based_intent(query)
240
+
241
+ chosen_intent = keyword_intent
242
+ confidence = keyword_confidence
243
+
244
+ # Nếu model tự tin và không mâu thuẫn với keyword, ưu tiên model
245
+ if model_intent and model_confidence >= 0.65:
246
+ if keyword_intent in {model_intent, "general_query", "greeting"}:
247
+ chosen_intent = model_intent
248
+ confidence = max(confidence, model_confidence)
249
+
250
+ # Ensemble: combine model and keyword predictions
251
+ if model_intent and keyword_intent:
252
+ if model_intent == keyword_intent:
253
+ # Both agree - boost confidence
254
+ confidence = min(1.0, (model_confidence + keyword_confidence) / 2 + 0.1)
255
+ elif model_confidence > 0.7 and keyword_confidence < 0.6:
256
+ # Model is more confident - use model
257
+ chosen_intent = model_intent
258
+ confidence = model_confidence * 0.9 # Slight penalty for disagreement
259
+
260
+ # Special handling for greeting - only if really simple
261
+ if keyword_intent == "greeting":
262
+ query_lower = query.lower().strip()
263
+ query_ascii = self._remove_accents(query_lower)
264
+ query_words = query_lower.split()
265
+ # Double-check: if query has fine keywords, it's NOT a greeting
266
+ fine_indicators = ["phạt", "mức", "vuot", "vượt", "đèn", "den", "vi phạm", "vi pham"]
267
+ if any(self._keyword_in(query_lower, query_ascii, indicator) for indicator in fine_indicators):
268
+ # Re-check with fine keywords
269
+ for kw in ["mức phạt", "vi phạm", "đèn đỏ", "vượt đèn", "muc phat", "vuot den", "phat", "vuot", "den", "muc"]:
270
+ if self._keyword_in(query_lower, query_ascii, kw):
271
+ return ("search_fine", 0.9)
272
+ # Only return greeting if query is very short (<= 3 words)
273
+ if len(query_words) > 3:
274
+ # If long query classified as greeting, it's probably wrong - use general
275
+ return ("general_query", 0.5)
276
+
277
+ # Ưu tiên intent pháp luật nếu có nhiều tín hiệu liên quan DB
278
+ query_lower_for_boost = query.lower()
279
+ if "search_legal" in {model_intent, keyword_intent}:
280
+ if any(kw in query_lower_for_boost for kw in LEGAL_KEYWORDS):
281
+ chosen_intent = "search_legal"
282
+ confidence = max(confidence, model_confidence, keyword_confidence, 0.8)
283
+
284
+ # Confidence calibration: adjust confidence based on query characteristics
285
+ confidence = self._calibrate_confidence(chosen_intent, confidence, query)
286
+
287
+ return (chosen_intent, confidence)
288
+
289
+ def _calibrate_confidence(self, intent: str, base_confidence: float, query: str) -> float:
290
+ """
291
+ Calibrate confidence score based on query characteristics.
292
+
293
+ Args:
294
+ intent: Classified intent.
295
+ base_confidence: Base confidence score.
296
+ query: Original query.
297
+
298
+ Returns:
299
+ Calibrated confidence score.
300
+ """
301
+ confidence = base_confidence
302
+ query_lower = query.lower()
303
+ query_words = query.split()
304
+
305
+ # Boost confidence for longer, more specific queries
306
+ if len(query_words) >= 5:
307
+ confidence = min(1.0, confidence + 0.05)
308
+
309
+ # Reduce confidence for very short queries
310
+ if len(query_words) <= 2:
311
+ confidence = max(0.3, confidence - 0.1)
312
+
313
+ # Boost confidence if query contains intent-specific keywords
314
+ intent_keywords = {
315
+ "search_fine": ["phạt", "mức phạt", "vi phạm"],
316
+ "search_procedure": ["thủ tục", "hồ sơ", "giấy tờ"],
317
+ "search_office": ["địa chỉ", "công an", "đơn vị"],
318
+ "search_advisory": ["cảnh báo", "lừa đảo", "scam"],
319
+ "search_legal": LEGAL_KEYWORDS,
320
+ }
321
+
322
+ if intent in intent_keywords:
323
+ keywords = intent_keywords[intent]
324
+ if any(kw in query_lower for kw in keywords):
325
+ confidence = min(1.0, confidence + 0.05)
326
+
327
+ return confidence
328
+
329
+ def _personalize_query(
330
+ self,
331
+ query: str,
332
+ intent: str,
333
+ context: Optional[Dict[str, Any]],
334
+ session_id: Optional[str]
335
+ ) -> str:
336
+ """
337
+ Personalize query based on user history and session context.
338
+
339
+ Args:
340
+ query: Original query.
341
+ intent: Detected intent.
342
+ context: Conversation context.
343
+ session_id: Session ID.
344
+
345
+ Returns:
346
+ Personalized query.
347
+ """
348
+ if not context or not session_id:
349
+ return query
350
+
351
+ # Get user preferences from context
352
+ entities = context.get("entities", {})
353
+ intents = context.get("intents", [])
354
+
355
+ # If user frequently asks about same intent, boost related terms
356
+ if intents and len(intents) >= 2:
357
+ most_common_intent = max(set(intents), key=intents.count)
358
+ if most_common_intent == intent:
359
+ # User prefers this intent - query is already personalized
360
+ pass
361
+
362
+ # Add context entities to query if missing
363
+ enhanced_parts = [query]
364
+
365
+ if intent == "search_fine" and "fine_code" in entities:
366
+ fine_code = entities["fine_code"]
367
+ if fine_code not in query.lower():
368
+ enhanced_parts.append(fine_code)
369
+
370
+ return " ".join(enhanced_parts)
371
+
372
+ def _model_based_intent(self, query: str) -> Tuple[Optional[str], float]:
373
+ """Phân loại ý định bằng model đã huấn luyện nếu có."""
374
+ if not self.intent_classifier:
375
+ return (None, 0.0)
376
+ try:
377
+ predicted_proba = getattr(self.intent_classifier, "predict_proba", None)
378
+ if not predicted_proba:
379
+ return (None, 0.0)
380
+ probs = predicted_proba([query])[0]
381
+ classes = self._intent_classes()
382
+ if not classes:
383
+ return (None, 0.0)
384
+ max_idx = int(np.argmax(probs))
385
+ return (classes[max_idx], float(probs[max_idx]))
386
+ except Exception:
387
+ return (None, 0.0)
388
+
389
+ def _intent_classes(self) -> Optional[List[str]]:
390
+ if not self.intent_classifier:
391
+ return None
392
+ if hasattr(self.intent_classifier, "classes_"):
393
+ return list(self.intent_classifier.classes_)
394
+ named_steps = getattr(self.intent_classifier, "named_steps", {})
395
+ clf = named_steps.get("clf") if isinstance(named_steps, dict) else None
396
+ if clf and hasattr(clf, "classes_"):
397
+ return list(clf.classes_)
398
+ return None
399
+
400
+ def _keyword_based_intent(self, query: str) -> Tuple[str, float]:
401
+ """Fallback keyword-based intent classification."""
402
+ # Use original query (lowercase) to preserve Vietnamese characters
403
+ query_lower = query.lower().strip()
404
+ query_ascii = self._remove_accents(query_lower)
405
+ query_words = query_lower.split()
406
+
407
+ # Check for keywords - prioritize fine-related queries FIRST
408
+ # Check on original query to preserve Vietnamese characters
409
+ # Check longer phrases first, then single words
410
+ fine_keywords = ["mức phạt", "vi phạm", "đèn đỏ", "nồng độ cồn", "mũ bảo hiểm", "tốc độ", "bằng lái", "vượt đèn", "mức phạt vượt"]
411
+ fine_keywords_ascii = [self._remove_accents(kw) for kw in fine_keywords]
412
+ fine_single_words = ["phạt", "vượt", "đèn", "mức", "phat", "vuot", "den"]
413
+
414
+ # Check multi-word keywords first
415
+ has_fine_keywords = False
416
+ for kw, kw_ascii in zip(fine_keywords, fine_keywords_ascii):
417
+ if self._keyword_in(query_lower, query_ascii, kw) or kw_ascii in query_ascii:
418
+ return ("search_fine", 0.95) # Very high confidence
419
+ # Then check single words - check ALL of them, not just first match
420
+ for kw in fine_single_words:
421
+ if self._keyword_in(query_lower, query_ascii, kw):
422
+ has_fine_keywords = True
423
+ # Return immediately if found
424
+ return ("search_fine", 0.9)
425
+
426
+ has_procedure_keywords = any(
427
+ self._keyword_in(query_lower, query_ascii, kw) for kw in
428
+ ["thủ tục", "hồ sơ", "điều kiện", "cư trú", "antt", "pccc", "thu tuc", "ho so", "dieu kien", "cu tru"]
429
+ )
430
+ if has_procedure_keywords:
431
+ return ("search_procedure", 0.8)
432
+
433
+ # Check advisory keywords first to avoid conflict with "công an" in office keywords
434
+ has_advisory_keywords = any(
435
+ self._keyword_in(query_lower, query_ascii, kw) for kw in
436
+ ["cảnh báo", "lừa đảo", "scam", "mạo danh", "thủ đoạn", "cảnh giác", "canh bao", "lua dao", "mao danh", "thu doan", "canh giac"]
437
+ )
438
+ if has_advisory_keywords:
439
+ return ("search_advisory", 0.8)
440
+
441
+ has_office_keywords = any(
442
+ self._keyword_in(query_lower, query_ascii, kw) for kw in
443
+ ["địa chỉ", "điểm tiếp dân", "công an", "số điện thoại", "giờ làm việc", "dia chi", "diem tiep dan", "cong an", "so dien thoai", "gio lam viec"]
444
+ )
445
+ if has_office_keywords:
446
+ return ("search_office", 0.8)
447
+
448
+ # Check legal keywords (check BEFORE advisory to avoid "công an" conflict)
449
+ has_legal_keywords = any(
450
+ self._keyword_in(query_lower, query_ascii, kw) for kw in
451
+ ["quyết định", "quy định", "thông tư", "nghị quyết", "văn bản pháp luật", "văn bản quy phạm", "điều lệnh",
452
+ "kỷ luật đảng viên", "kỷ luật", "xử lý kỷ luật", "hình thức kỷ luật", "mức kỷ luật",
453
+ "quyết định 69", "quyết định 264", "qd 69", "qd 264", "thông tư 02", "tt 02",
454
+ "quy định kỷ luật", "kỷ luật đảng", "k��� luật cán bộ", "xử lý vi phạm",
455
+ "quyet dinh", "quy dinh", "thong tu", "nghi quyet", "van ban phap luat", "van ban quy pham", "dieu lenh",
456
+ "ky luat dang vien", "ky luat", "xu ly ky luat", "hinh thuc ky luat", "muc ky luat",
457
+ "quyet dinh 69", "quyet dinh 264", "qd 69", "qd 264", "thong tu 02", "tt 02",
458
+ "quy dinh ky luat", "ky luat dang", "ky luat can bo", "xu ly vi pham"]
459
+ )
460
+ if has_legal_keywords:
461
+ return ("search_legal", 0.85)
462
+
463
+ # Only treat as greeting if it's VERY short (<= 3 words) and ONLY contains greeting words
464
+ # AND does NOT contain any other keywords
465
+ has_any_keyword = (has_fine_keywords or has_procedure_keywords or
466
+ has_office_keywords or has_advisory_keywords or has_legal_keywords)
467
+
468
+ if (len(query_words) <= 3 and
469
+ any(self._keyword_in(query_lower, query_ascii, kw) for kw in ["xin chào", "chào", "hello", "hi", "xin chao", "chao"]) and
470
+ not has_any_keyword):
471
+ return ("greeting", 0.9)
472
+
473
+ return ("general_query", 0.5)
474
+
475
+ def extract_keywords(self, query: str) -> List[str]:
476
+ """Extract keywords from query for search."""
477
+ # Remove common stopwords
478
+ stopwords = {"là", "gì", "bao nhiêu", "như thế nào", "ở đâu", "của", "và", "hoặc", "tôi", "bạn"}
479
+
480
+ words = re.findall(r'\b\w+\b', query.lower())
481
+ keywords = [w for w in words if w not in stopwords and len(w) > 2]
482
+
483
+ return keywords
484
+
485
+ def search_by_intent(self, intent: str, query: str, limit: int = 5) -> Dict[str, Any]:
486
+ """Search based on classified intent."""
487
+ # Use original query for better matching, especially for Vietnamese text
488
+ keywords = query.strip()
489
+ # Also try with extracted keywords as fallback
490
+ extracted = " ".join(self.extract_keywords(query))
491
+ if extracted and len(extracted) > 2:
492
+ keywords = f"{keywords} {extracted}"
493
+
494
+ results = []
495
+
496
+ if intent == "search_fine":
497
+ qs = Fine.objects.all()
498
+ text_fields = ["name", "code", "article", "decree", "remedial"]
499
+ search_results = search_with_ml(qs, keywords, text_fields, top_k=limit, min_score=0.1)
500
+ results = [{"type": "fine", "data": {
501
+ "id": f.id,
502
+ "name": f.name,
503
+ "code": f.code,
504
+ "min_fine": float(f.min_fine) if f.min_fine else None,
505
+ "max_fine": float(f.max_fine) if f.max_fine else None,
506
+ "fine_amount_formatted": format_fine_amount(
507
+ float(f.min_fine) if f.min_fine else None,
508
+ float(f.max_fine) if f.max_fine else None
509
+ ),
510
+ "article": f.article,
511
+ "decree": f.decree,
512
+ }} for f in search_results]
513
+
514
+ elif intent == "search_procedure":
515
+ qs = Procedure.objects.all()
516
+ text_fields = ["title", "domain", "conditions", "dossier"]
517
+ search_results = search_with_ml(qs, keywords, text_fields, top_k=limit, min_score=0.1)
518
+ results = [{"type": "procedure", "data": {
519
+ "id": p.id,
520
+ "title": p.title,
521
+ "domain": p.domain,
522
+ "level": p.level,
523
+ }} for p in search_results]
524
+
525
+ elif intent == "search_office":
526
+ qs = Office.objects.all()
527
+ text_fields = ["unit_name", "address", "district", "service_scope"]
528
+ search_results = search_with_ml(qs, keywords, text_fields, top_k=limit, min_score=0.1)
529
+ results = [{"type": "office", "data": {
530
+ "id": o.id,
531
+ "unit_name": o.unit_name,
532
+ "address": o.address,
533
+ "district": o.district,
534
+ "phone": o.phone,
535
+ "working_hours": o.working_hours,
536
+ }} for o in search_results]
537
+
538
+ elif intent == "search_advisory":
539
+ qs = Advisory.objects.all()
540
+ text_fields = ["title", "summary"]
541
+ search_results = search_with_ml(qs, keywords, text_fields, top_k=limit, min_score=0.1)
542
+ results = [{"type": "advisory", "data": {
543
+ "id": a.id,
544
+ "title": a.title,
545
+ "summary": a.summary,
546
+ }} for a in search_results]
547
+
548
+ return {
549
+ "intent": intent,
550
+ "query": query,
551
+ "keywords": keywords,
552
+ "results": results,
553
+ "count": len(results)
554
+ }
555
+
556
+ def _serialize_document(self, doc: Any, content_type: str) -> Dict[str, Any]:
557
+ """Convert Django model instance to JSON-serializable dict."""
558
+ base = {"id": getattr(doc, "id", None)}
559
+ content_type = (content_type or "").lower()
560
+
561
+ def _to_iso(value):
562
+ if value is None:
563
+ return None
564
+ if hasattr(value, "isoformat"):
565
+ return value.isoformat()
566
+ return value
567
+
568
+ if content_type == "procedure":
569
+ base.update({
570
+ "title": getattr(doc, "title", ""),
571
+ "domain": getattr(doc, "domain", ""),
572
+ "level": getattr(doc, "level", ""),
573
+ "conditions": getattr(doc, "conditions", ""),
574
+ "dossier": getattr(doc, "dossier", ""),
575
+ "fee": getattr(doc, "fee", ""),
576
+ "duration": getattr(doc, "duration", ""),
577
+ "authority": getattr(doc, "authority", ""),
578
+ "source_url": getattr(doc, "source_url", ""),
579
+ })
580
+ elif content_type == "fine":
581
+ min_fine = float(doc.min_fine) if getattr(doc, "min_fine", None) is not None else None
582
+ max_fine = float(doc.max_fine) if getattr(doc, "max_fine", None) is not None else None
583
+ base.update({
584
+ "name": getattr(doc, "name", ""),
585
+ "code": getattr(doc, "code", ""),
586
+ "min_fine": min_fine,
587
+ "max_fine": max_fine,
588
+ "fine_amount_formatted": format_fine_amount(min_fine, max_fine),
589
+ "article": getattr(doc, "article", ""),
590
+ "decree": getattr(doc, "decree", ""),
591
+ })
592
+ elif content_type == "office":
593
+ base.update({
594
+ "unit_name": getattr(doc, "unit_name", ""),
595
+ "address": getattr(doc, "address", ""),
596
+ "district": getattr(doc, "district", ""),
597
+ "phone": getattr(doc, "phone", ""),
598
+ "working_hours": getattr(doc, "working_hours", ""),
599
+ })
600
+ elif content_type == "advisory":
601
+ base.update({
602
+ "title": getattr(doc, "title", ""),
603
+ "summary": getattr(doc, "summary", ""),
604
+ "source_url": getattr(doc, "source_url", ""),
605
+ "published_at": _to_iso(getattr(doc, "published_at", None)),
606
+ })
607
+ else:
608
+ # Fallback: include common attributes but skip non-serializable ones
609
+ safe_attrs = [
610
+ "title", "summary", "description", "domain", "level", "conditions",
611
+ "dossier", "fee", "duration", "authority", "unit_name", "address",
612
+ "district", "phone", "working_hours", "source_url", "published_at"
613
+ ]
614
+ for attr in safe_attrs:
615
+ if hasattr(doc, attr):
616
+ value = getattr(doc, attr)
617
+ if attr == "published_at":
618
+ base[attr] = _to_iso(value)
619
+ elif isinstance(value, (str, int, float, type(None))):
620
+ base[attr] = value
621
+
622
+ return base
623
+
624
+ def generate_response(self, query: str, session_id: Optional[str] = None) -> Dict[str, Any]:
625
+ """
626
+ Generate chatbot response for user query with context awareness.
627
+
628
+ Args:
629
+ query: User query string.
630
+ session_id: Optional session ID for context management.
631
+
632
+ Returns:
633
+ Dict with message, intent, results, and session_id.
634
+ """
635
+ query = query.strip()
636
+ original_query = query
637
+
638
+ # Get context if session_id provided
639
+ context_messages = []
640
+ context_dict = None
641
+ if session_id:
642
+ try:
643
+ from hue_portal.chatbot.context_manager import ConversationContext
644
+ from hue_portal.chatbot.entity_extraction import resolve_pronouns, extract_all_entities
645
+
646
+ # Get recent messages
647
+ recent_messages = ConversationContext.get_recent_messages(session_id, limit=10)
648
+ context_messages = [
649
+ {
650
+ "role": msg.role,
651
+ "content": msg.content,
652
+ "intent": msg.intent,
653
+ "entities": msg.entities
654
+ }
655
+ for msg in recent_messages
656
+ ]
657
+
658
+ # Build context dictionary for intent classification
659
+ context_dict = ConversationContext.get_context_summary(session_id, max_messages=5)
660
+
661
+ # Resolve pronouns in query
662
+ if context_messages:
663
+ query = resolve_pronouns(query, context_messages)
664
+ if query != original_query:
665
+ print(f"Query enhanced with context: '{original_query}' -> '{query}'")
666
+ except Exception as e:
667
+ print(f"Error loading context: {e}")
668
+
669
+ # Classify intent FIRST (use enhanced query and context)
670
+ intent, confidence = self.classify_intent(query, context=context_dict)
671
+
672
+ # Personalize response based on context and user history
673
+ personalized_query = self._personalize_query(query, intent, context_dict, session_id)
674
+ if personalized_query != query:
675
+ query = personalized_query
676
+
677
+ # Only handle greetings if it's REALLY a simple greeting (very short, no other keywords)
678
+ query_lower = query.lower().strip()
679
+ query_words = query_lower.split()
680
+
681
+ # Check if it contains keywords that indicate it's NOT a greeting
682
+ has_fine_keywords = any(kw in query_lower for kw in ["phạt", "mức phạt", "vi phạm", "đèn đỏ", "nồng độ cồn", "mũ bảo hiểm", "tốc độ", "vượt"])
683
+ has_procedure_keywords = any(kw in query_lower for kw in ["thủ tục", "hồ sơ", "điều kiện", "cư trú", "antt", "pccc"])
684
+ # Check advisory keywords first to avoid conflict with "công an" in office keywords
685
+ has_advisory_keywords = any(kw in query_lower for kw in ["cảnh báo", "lừa đảo", "scam", "mạo danh", "thủ đoạn", "cảnh giác"])
686
+ has_office_keywords = any(kw in query_lower for kw in ["địa chỉ", "công an", "số điện thoại", "giờ làm việc"])
687
+ has_legal_keywords = any(kw in query_lower for kw in ["quyết định", "quy định", "thông tư", "kỷ luật đảng viên", "kỷ luật", "qd 69", "qd 264", "thông tư 02", "điều lệnh", "văn bản pháp luật"])
688
+
689
+ # Only treat as greeting if it's very short AND has no other keywords AND classified as greeting
690
+ is_simple_greeting = (len(query_words) <= 3 and
691
+ any(greeting in query_lower for greeting in ["xin chào", "chào", "hello", "hi"]) and
692
+ not (has_fine_keywords or has_procedure_keywords or has_office_keywords or has_advisory_keywords or has_legal_keywords))
693
+
694
+ if is_simple_greeting and intent == "greeting":
695
+ response = {
696
+ "message": RESPONSE_TEMPLATES["greeting"],
697
+ "intent": "greeting",
698
+ "results": [],
699
+ "count": 0,
700
+ "session_id": session_id
701
+ }
702
+
703
+ # Save conversation if session_id provided
704
+ if session_id:
705
+ try:
706
+ from hue_portal.chatbot.context_manager import ConversationContext
707
+ from hue_portal.chatbot.entity_extraction import extract_all_entities
708
+
709
+ # Save user message
710
+ entities = extract_all_entities(original_query)
711
+ ConversationContext.add_message(
712
+ session_id=session_id,
713
+ role="user",
714
+ content=original_query,
715
+ intent=intent,
716
+ entities=entities
717
+ )
718
+
719
+ # Save bot response
720
+ ConversationContext.add_message(
721
+ session_id=session_id,
722
+ role="bot",
723
+ content=RESPONSE_TEMPLATES["greeting"],
724
+ intent=intent
725
+ )
726
+ except Exception as e:
727
+ print(f"Error saving conversation: {e}")
728
+
729
+ return response
730
+
731
+ # Try RAG pipeline first (if embeddings available)
732
+ use_rag = True
733
+ try:
734
+ from hue_portal.core.rag import rag_pipeline
735
+ # Build context list for RAG
736
+ rag_context = None
737
+ if context_messages:
738
+ rag_context = context_messages
739
+ rag_result = rag_pipeline(query, intent, top_k=5, min_confidence=confidence, context=rag_context, use_llm=True)
740
+
741
+ # Use RAG answer if available (even with count=0 for general conversation)
742
+ if rag_result.get("answer") and (rag_result["count"] > 0 or rag_result.get("answer", "").strip()):
743
+ # Use RAG-generated answer
744
+ documents = rag_result["documents"][:5]
745
+ results = [
746
+ {
747
+ "type": rag_result["content_type"],
748
+ "data": self._serialize_document(doc, rag_result["content_type"])
749
+ } for doc in documents
750
+ ]
751
+
752
+ # Add best_match flag and relevance_scores
753
+ best_match_index = 0 if documents else None
754
+ relevance_scores = []
755
+ for i, doc in enumerate(documents):
756
+ score = getattr(doc, "_hybrid_score", getattr(doc, "_ml_score", 0.0))
757
+ relevance_scores.append({
758
+ "index": i,
759
+ "score": float(score) if score else 0.0,
760
+ "is_best_match": i == 0
761
+ })
762
+
763
+ response = {
764
+ "message": rag_result["answer"],
765
+ "intent": intent,
766
+ "confidence": rag_result["confidence"],
767
+ "results": results,
768
+ "count": rag_result["count"],
769
+ "best_match": best_match_index,
770
+ "relevance_scores": relevance_scores,
771
+ "session_id": session_id
772
+ }
773
+
774
+ # Save conversation if session_id provided
775
+ if session_id:
776
+ try:
777
+ from hue_portal.chatbot.context_manager import ConversationContext
778
+ from hue_portal.chatbot.entity_extraction import extract_all_entities
779
+
780
+ # Save user message
781
+ entities = extract_all_entities(original_query)
782
+ ConversationContext.add_message(
783
+ session_id=session_id,
784
+ role="user",
785
+ content=original_query,
786
+ intent=intent,
787
+ entities=entities
788
+ )
789
+
790
+ # Save bot response
791
+ ConversationContext.add_message(
792
+ session_id=session_id,
793
+ role="bot",
794
+ content=rag_result["answer"],
795
+ intent=intent
796
+ )
797
+ except Exception as e:
798
+ print(f"Error saving conversation: {e}")
799
+
800
+ return response
801
+ except Exception as e:
802
+ # Fallback to original search if RAG fails
803
+ print(f"RAG pipeline not available, using original search: {e}")
804
+ use_rag = False
805
+
806
+ # Search based on intent (original method)
807
+ search_result = self.search_by_intent(intent, query, limit=5)
808
+
809
+ # Generate response message
810
+ if search_result["count"] > 0:
811
+ template = RESPONSE_TEMPLATES.get(intent, RESPONSE_TEMPLATES["general_query"])
812
+ message = template.format(
813
+ count=search_result["count"],
814
+ query=query
815
+ )
816
+ else:
817
+ message = RESPONSE_TEMPLATES["no_results"].format(query=query)
818
+
819
+ # Add best_match flag and relevance_scores for search results
820
+ best_match_index = 0 if search_result["count"] > 0 else None
821
+ relevance_scores = []
822
+ for i, result in enumerate(search_result["results"][:5]):
823
+ # Try to get score from result data if available
824
+ score = 0.0
825
+ if isinstance(result, dict) and "data" in result:
826
+ # Score might be in the data or we can infer from position
827
+ score = 1.0 - (i * 0.1) # Decreasing score for lower positions
828
+ relevance_scores.append({
829
+ "index": i,
830
+ "score": score,
831
+ "is_best_match": i == 0
832
+ })
833
+
834
+ response = {
835
+ "message": message,
836
+ "intent": intent,
837
+ "confidence": confidence,
838
+ "results": search_result["results"],
839
+ "count": search_result["count"],
840
+ "best_match": best_match_index,
841
+ "relevance_scores": relevance_scores,
842
+ "session_id": session_id
843
+ }
844
+
845
+ # Save conversation if session_id provided
846
+ if session_id:
847
+ try:
848
+ from hue_portal.chatbot.context_manager import ConversationContext
849
+ from hue_portal.chatbot.entity_extraction import extract_all_entities
850
+
851
+ # Save user message
852
+ entities = extract_all_entities(original_query)
853
+ ConversationContext.add_message(
854
+ session_id=session_id,
855
+ role="user",
856
+ content=original_query,
857
+ intent=intent,
858
+ entities=entities
859
+ )
860
+
861
+ # Save bot response
862
+ ConversationContext.add_message(
863
+ session_id=session_id,
864
+ role="bot",
865
+ content=message,
866
+ intent=intent
867
+ )
868
+ except Exception as e:
869
+ print(f"Error saving conversation: {e}")
870
+
871
+ return response
872
+
873
+
874
+ # Global chatbot instance
875
+ _chatbot_instance = None
876
+
877
+ def get_chatbot() -> Chatbot:
878
+ """Get or create chatbot instance."""
879
+ global _chatbot_instance
880
+ if _chatbot_instance is None:
881
+ _chatbot_instance = Chatbot()
882
+ return _chatbot_instance