davidtran999 commited on
Commit
31f8e67
·
verified ·
1 Parent(s): dc32db8

Upload backend/chatbot/advanced_features.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/chatbot/advanced_features.py +185 -0
backend/chatbot/advanced_features.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Advanced features for chatbot: follow-up suggestions, ambiguity detection, explanations.
3
+ """
4
+ from typing import List, Dict, Any, Optional
5
+ from hue_portal.core.models import Fine, Procedure, Office, Advisory
6
+
7
+
8
+ def suggest_follow_up_questions(query: str, results: List[Any], intent: str) -> List[str]:
9
+ """
10
+ Suggest follow-up questions based on query and results.
11
+
12
+ Args:
13
+ query: Original query.
14
+ results: Retrieved results.
15
+ intent: Detected intent.
16
+
17
+ Returns:
18
+ List of suggested follow-up questions.
19
+ """
20
+ suggestions = []
21
+
22
+ if intent == "search_fine":
23
+ if results:
24
+ # Suggest questions about related fines
25
+ suggestions.append("Còn mức phạt nào khác không?")
26
+ suggestions.append("Điều luật liên quan là gì?")
27
+ suggestions.append("Biện pháp khắc phục như thế nào?")
28
+ else:
29
+ suggestions.append("Bạn có thể cho biết cụ thể loại vi phạm không?")
30
+
31
+ elif intent == "search_procedure":
32
+ if results:
33
+ suggestions.append("Hồ sơ cần chuẩn bị gì?")
34
+ suggestions.append("Lệ phí là bao nhiêu?")
35
+ suggestions.append("Thời hạn xử lý là bao lâu?")
36
+ suggestions.append("Nộp hồ sơ ở đâu?")
37
+ else:
38
+ suggestions.append("Bạn muốn tìm thủ tục nào cụ thể?")
39
+
40
+ elif intent == "search_office":
41
+ if results:
42
+ suggestions.append("Số điện thoại liên hệ?")
43
+ suggestions.append("Giờ làm việc như thế nào?")
44
+ suggestions.append("Địa chỉ cụ thể ở đâu?")
45
+ else:
46
+ suggestions.append("Bạn muốn tìm đơn vị nào?")
47
+
48
+ elif intent == "search_advisory":
49
+ if results:
50
+ suggestions.append("Còn cảnh báo nào khác không?")
51
+ suggestions.append("Cách phòng tránh như thế nào?")
52
+ else:
53
+ suggestions.append("Bạn muốn tìm cảnh báo về chủ đề gì?")
54
+
55
+ return suggestions[:3] # Return top 3 suggestions
56
+
57
+
58
+ def detect_ambiguity(query: str, results_count: int, confidence: float) -> Tuple[bool, Optional[str]]:
59
+ """
60
+ Detect if query is ambiguous.
61
+
62
+ Args:
63
+ query: User query.
64
+ results_count: Number of results found.
65
+ confidence: Confidence score.
66
+
67
+ Returns:
68
+ Tuple of (is_ambiguous, ambiguity_reason).
69
+ """
70
+ query_lower = query.lower()
71
+ query_words = query.split()
72
+
73
+ # Very short queries are often ambiguous
74
+ if len(query_words) <= 2:
75
+ return (True, "Câu hỏi quá ngắn, cần thêm thông tin")
76
+
77
+ # Low confidence and many results suggests ambiguity
78
+ if results_count > 10 and confidence < 0.5:
79
+ return (True, "Kết quả quá nhiều, cần cụ thể hơn")
80
+
81
+ # Very generic queries
82
+ generic_queries = ["thông tin", "tìm kiếm", "hỏi", "giúp"]
83
+ if any(gq in query_lower for gq in generic_queries) and len(query_words) <= 3:
84
+ return (True, "Câu hỏi chung chung, cần cụ thể hơn")
85
+
86
+ return (False, None)
87
+
88
+
89
+ def generate_explanation(result: Any, query: str, score: Optional[float] = None) -> str:
90
+ """
91
+ Generate explanation for why a result is relevant.
92
+
93
+ Args:
94
+ result: Result object.
95
+ result_type: Type of result.
96
+ query: Original query.
97
+ score: Relevance score.
98
+
99
+ Returns:
100
+ Explanation string.
101
+ """
102
+ result_type = type(result).__name__.lower()
103
+ explanation_parts = []
104
+
105
+ if "fine" in result_type:
106
+ name = getattr(result, "name", "")
107
+ code = getattr(result, "code", "")
108
+ explanation_parts.append(f"Kết quả này phù hợp vì:")
109
+ if code:
110
+ explanation_parts.append(f"- Mã vi phạm: {code}")
111
+ if name:
112
+ explanation_parts.append(f"- Tên vi phạm: {name}")
113
+ if score:
114
+ explanation_parts.append(f"- Độ phù hợp: {score:.0%}")
115
+
116
+ elif "procedure" in result_type:
117
+ title = getattr(result, "title", "")
118
+ explanation_parts.append(f"Kết quả này phù hợp vì:")
119
+ if title:
120
+ explanation_parts.append(f"- Tên thủ tục: {title}")
121
+ if score:
122
+ explanation_parts.append(f"- Độ phù hợp: {score:.0%}")
123
+
124
+ elif "office" in result_type:
125
+ unit_name = getattr(result, "unit_name", "")
126
+ explanation_parts.append(f"Kết quả này phù hợp vì:")
127
+ if unit_name:
128
+ explanation_parts.append(f"- Tên đơn vị: {unit_name}")
129
+ if score:
130
+ explanation_parts.append(f"- Độ phù hợp: {score:.0%}")
131
+
132
+ elif "advisory" in result_type:
133
+ title = getattr(result, "title", "")
134
+ explanation_parts.append(f"Kết quả này phù hợp vì:")
135
+ if title:
136
+ explanation_parts.append(f"- Tiêu đề: {title}")
137
+ if score:
138
+ explanation_parts.append(f"- Độ phù hợp: {score:.0%}")
139
+
140
+ return "\n".join(explanation_parts) if explanation_parts else "Kết quả này phù hợp với câu hỏi của bạn."
141
+
142
+
143
+ def compare_results(results: List[Any], result_type: str) -> str:
144
+ """
145
+ Compare multiple results and highlight differences.
146
+
147
+ Args:
148
+ results: List of result objects.
149
+ result_type: Type of results.
150
+
151
+ Returns:
152
+ Comparison summary string.
153
+ """
154
+ if len(results) < 2:
155
+ return ""
156
+
157
+ comparison_parts = ["So sánh các kết quả:"]
158
+
159
+ if result_type == "fine":
160
+ # Compare fine amounts
161
+ fine_amounts = []
162
+ for result in results[:3]:
163
+ if hasattr(result, "min_fine") and hasattr(result, "max_fine"):
164
+ if result.min_fine and result.max_fine:
165
+ fine_amounts.append(f"{result.name}: {result.min_fine:,.0f} - {result.max_fine:,.0f} VNĐ")
166
+
167
+ if fine_amounts:
168
+ comparison_parts.extend(fine_amounts)
169
+
170
+ elif result_type == "procedure":
171
+ # Compare procedures by domain/level
172
+ for result in results[:3]:
173
+ title = getattr(result, "title", "")
174
+ domain = getattr(result, "domain", "")
175
+ level = getattr(result, "level", "")
176
+ if title:
177
+ comp = f"- {title}"
178
+ if domain:
179
+ comp += f" ({domain})"
180
+ if level:
181
+ comp += f" - Cấp {level}"
182
+ comparison_parts.append(comp)
183
+
184
+ return "\n".join(comparison_parts)
185
+