quick fix timestamp
Browse files- app/message_processor.py +19 -69
app/message_processor.py
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
from typing import Dict, Any, List, Optional
|
| 2 |
import asyncio
|
| 3 |
import traceback
|
|
|
|
| 4 |
from loguru import logger
|
| 5 |
from .constants import SUMMARY_STATUS_MESSAGES, PROCESSING_STATUS_MESSAGES, FOUND_REGULATIONS_MESSAGES, BATCH_STATUS_MESSAGES
|
| 6 |
from .utils import get_random_message
|
| 7 |
from .facebook import FacebookClient
|
| 8 |
from app.config import get_settings
|
| 9 |
import re
|
| 10 |
-
import json
|
| 11 |
|
| 12 |
class MessageProcessor:
|
| 13 |
def __init__(self, channel, sender_id):
|
|
@@ -180,14 +180,24 @@ class MessageProcessor:
|
|
| 180 |
conversation_context = []
|
| 181 |
total_chars = 0
|
| 182 |
|
| 183 |
-
#
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
if isinstance(
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
# Bước 2: Duyệt từ mới -> cũ để loại bỏ message cũ nếu cần
|
| 193 |
for row in reversed(sorted_history):
|
|
@@ -241,8 +251,6 @@ class MessageProcessor:
|
|
| 241 |
return
|
| 242 |
|
| 243 |
def flatten_timestamp(self, ts):
|
| 244 |
-
# if isinstance(ts, int):
|
| 245 |
-
# return ts
|
| 246 |
flat = []
|
| 247 |
if not isinstance(ts, list):
|
| 248 |
ts = [ts]
|
|
@@ -272,14 +280,6 @@ class MessageProcessor:
|
|
| 272 |
try:
|
| 273 |
reranked = await self.channel.reranker.rerank(question, matches, top_k=10)
|
| 274 |
if reranked:
|
| 275 |
-
# Gửi Facebook message sau khi hoàn thành
|
| 276 |
-
# Tạm comment đi để test
|
| 277 |
-
# if self.facebook:
|
| 278 |
-
# try:
|
| 279 |
-
# message = get_random_message(BATCH_STATUS_MESSAGES)
|
| 280 |
-
# await self.facebook.send_message(message=f"... {message} ...")
|
| 281 |
-
# except Exception as e:
|
| 282 |
-
# logger.error(f"[RERANK][FACEBOOK] Error sending batch message: {e}")
|
| 283 |
matches = reranked
|
| 284 |
except Exception as e:
|
| 285 |
logger.error(f"[RERANK] Lỗi khi rerank: {e}")
|
|
@@ -296,18 +296,6 @@ class MessageProcessor:
|
|
| 296 |
if not top or (match.get('similarity', 0) > top.get('similarity', 0)):
|
| 297 |
top = match
|
| 298 |
full_result_text += f"\n{(match.get('structure') or '').strip()}:\n"
|
| 299 |
-
# tieude = (match.get('tieude') or '').strip()
|
| 300 |
-
# noidung = (match.get('noidung') or '').strip()
|
| 301 |
-
# hanhvi = (tieude + "\n" + noidung).strip().replace('\n', ' ')
|
| 302 |
-
# full_result_text += f"Thực hiện hành vi:\n{hanhvi}"
|
| 303 |
-
# canhantu = arr_to_str(match.get('canhantu'))
|
| 304 |
-
# canhanden = arr_to_str(match.get('canhanden'))
|
| 305 |
-
# if canhantu or canhanden:
|
| 306 |
-
# full_result_text += f"\nCá nhân sẽ bị phạt tiền từ {canhantu} VNĐ đến {canhanden} VNĐ"
|
| 307 |
-
# tochuctu = arr_to_str(match.get('tochuctu'))
|
| 308 |
-
# tochucden = arr_to_str(match.get('tochucden'))
|
| 309 |
-
# if tochuctu or tochucden:
|
| 310 |
-
# full_result_text += f"\nTổ chức sẽ bị phạt tiền từ {tochuctu} VNĐ đến {tochucden} VNĐ"
|
| 311 |
fullContent = (match.get('fullcontent') or '').strip()
|
| 312 |
full_result_text += f"{fullContent}"
|
| 313 |
hpbsnoidung = arr_to_str(match.get('hpbsnoidung'), sep="; ")
|
|
@@ -321,18 +309,6 @@ class MessageProcessor:
|
|
| 321 |
full_result_text += f"\nTạm giữ phương tiên: 07 ngày"
|
| 322 |
if top and (top.get('tieude') or top.get('noidung')):
|
| 323 |
top_result_text += f"\n{(match.get('structure') or '').strip()}:\n"
|
| 324 |
-
# tieude = (top.get('tieude') or '').strip()
|
| 325 |
-
# noidung = (top.get('noidung') or '').strip()
|
| 326 |
-
# hanhvi = (tieude + "\n" + noidung).strip().replace('\n', ' ')
|
| 327 |
-
# top_result_text += f"Thực hiện hành vi:\n{hanhvi}"
|
| 328 |
-
# canhantu = arr_to_str(top.get('canhantu'))
|
| 329 |
-
# canhanden = arr_to_str(top.get('canhanden'))
|
| 330 |
-
# if canhantu or canhanden:
|
| 331 |
-
# top_result_text += f"\nCá nhân sẽ bị phạt tiền từ {canhantu} VNĐ đến {canhanden} VNĐ"
|
| 332 |
-
# tochuctu = arr_to_str(top.get('tochuctu'))
|
| 333 |
-
# tochucden = arr_to_str(top.get('tochucden'))
|
| 334 |
-
# if tochuctu or tochucden:
|
| 335 |
-
# top_result_text += f"\nTổ chức sẽ bị phạt tiền từ {tochuctu} VNĐ đến {tochucden} VNĐ"
|
| 336 |
fullContent = (match.get('fullcontent') or '').strip()
|
| 337 |
top_result_text += f"{fullContent}"
|
| 338 |
hpbsnoidung = arr_to_str(top.get('hpbsnoidung'), sep="; ")
|
|
@@ -374,18 +350,6 @@ class MessageProcessor:
|
|
| 374 |
fallback = "Tóm tắt các đoạn luật liên quan:\n\n"
|
| 375 |
for i, match in enumerate(matches, 1):
|
| 376 |
fallback += f"\n{(match.get('structure') or '').strip()}:\n"
|
| 377 |
-
# tieude = (match.get('tieude') or '').strip()
|
| 378 |
-
# noidung = (match.get('noidung') or '').strip()
|
| 379 |
-
# if tieude or noidung:
|
| 380 |
-
# fallback += f" - Hành vi: {(tieude + ' ' + noidung).strip()}\n"
|
| 381 |
-
# canhantu = arr_to_str(match.get('canhantu'))
|
| 382 |
-
# canhanden = arr_to_str(match.get('canhanden'))
|
| 383 |
-
# if canhantu or canhanden:
|
| 384 |
-
# fallback += f" - Cá nhân bị phạt tiền từ {canhantu} VNĐ đến {canhanden} VNĐ\n"
|
| 385 |
-
# tochuctu = arr_to_str(match.get('tochuctu'))
|
| 386 |
-
# tochucden = arr_to_str(match.get('tochucden'))
|
| 387 |
-
# if tochuctu or tochucden:
|
| 388 |
-
# fallback += f" - Tổ chức bị phạt tiền từ {tochuctu} VNĐ đến {tochucden} VNĐ\n"
|
| 389 |
fullContent = (match.get('fullcontent') or '').strip()
|
| 390 |
fallback += f"{fullContent}"
|
| 391 |
hpbsnoidung = arr_to_str(match.get('hpbsnoidung'), sep="; ")
|
|
@@ -404,25 +368,20 @@ class MessageProcessor:
|
|
| 404 |
logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
|
| 405 |
return "https://facebook.com/mock_post_url"
|
| 406 |
|
| 407 |
-
# <<< FIX LỖI 1 TẠI ĐÂY >>>
|
| 408 |
async def handle_muc_phat(self, conv, conversation_context, page_token, sender_id):
|
| 409 |
vehicle = conv.get('originalvehicle', '')
|
| 410 |
action = conv.get('originalaction', '')
|
| 411 |
question = conv.get('originalquestion', '')
|
| 412 |
keywords = [kw.strip() for kw in vehicle.split(',') if kw.strip()]
|
| 413 |
-
#remove the requirement of having to have vehicle
|
| 414 |
-
# if keywords:
|
| 415 |
if question:
|
| 416 |
logger.info(f"[DEBUG] tạo embedding: {action}")
|
| 417 |
embedding = await self.channel.embedder.create_embedding(action)
|
| 418 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
| 419 |
-
# Lấy match_count từ config
|
| 420 |
from app.config import get_settings
|
| 421 |
match_count = get_settings().match_count
|
| 422 |
matches = self.channel.supabase.match_documents(
|
| 423 |
embedding,
|
| 424 |
match_count=match_count,
|
| 425 |
-
# vehicle_keywords=keywords,
|
| 426 |
user_question=action
|
| 427 |
)
|
| 428 |
logger.info(f"[DEBUG] matches: {matches}")
|
|
@@ -434,16 +393,12 @@ class MessageProcessor:
|
|
| 434 |
logger.info(f"[DEBUG] Không có hành vi vi phạm: {question}")
|
| 435 |
response = "Xin lỗi, tôi không tìm thấy thông tin về hành vi vi phạm trong câu hỏi của bạn."
|
| 436 |
conv['isdone'] = True
|
| 437 |
-
# else:
|
| 438 |
-
# response = "Vui lòng cho biết loại phương tiện bạn cần tìm (xe máy, ô tô...)"
|
| 439 |
-
# conv['isdone'] = False
|
| 440 |
return response
|
| 441 |
|
| 442 |
async def handle_quy_tac(self, conv, conversation_context, message_text):
|
| 443 |
prompt = (
|
| 444 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 445 |
f"Lịch sử:\n{conversation_context}"
|
| 446 |
-
|
| 447 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 448 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 449 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
@@ -456,7 +411,6 @@ class MessageProcessor:
|
|
| 456 |
prompt = (
|
| 457 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 458 |
f"Lịch sử:\n{conversation_context}"
|
| 459 |
-
|
| 460 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 461 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 462 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
@@ -469,7 +423,6 @@ class MessageProcessor:
|
|
| 469 |
prompt = (
|
| 470 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 471 |
f"Lịch sử:\n{conversation_context}"
|
| 472 |
-
|
| 473 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 474 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 475 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
@@ -479,11 +432,9 @@ class MessageProcessor:
|
|
| 479 |
return answer.strip() if answer and answer.strip() else "[Đang phát triển] Tính năng trả lời về quy trình xử lý vi phạm giao thông sẽ sớm có mặt."
|
| 480 |
|
| 481 |
async def handle_ca_nhan(self, conv, conversation_context, message_text):
|
| 482 |
-
# Nếu câu hỏi là về thông tin cá nhân của bot, hướng dẫn LLM trả lời đúng
|
| 483 |
prompt = (
|
| 484 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 485 |
f"Lịch sử:\n{conversation_context}"
|
| 486 |
-
|
| 487 |
'Với các thông tin sau: "Bạn có tên là WeThoong AI, là trợ lý giao thông thông minh. Bạn được anh Viet Cat tạo ra và facebook cá nhân của anh ý là https://facebook.com/vietcat". '
|
| 488 |
'Không được trả lời bạn là AI của Google, OpenAI, hay bất kỳ hãng nào khác. '
|
| 489 |
'Hãy trả lời thông minh, hài hước, ngắn gọn cho câu hỏi sau:\n'
|
|
@@ -497,7 +448,6 @@ class MessageProcessor:
|
|
| 497 |
prompt = (
|
| 498 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 499 |
f"Lịch sử:\n{conversation_context}"
|
| 500 |
-
|
| 501 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 502 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 503 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
|
|
| 1 |
from typing import Dict, Any, List, Optional
|
| 2 |
import asyncio
|
| 3 |
import traceback
|
| 4 |
+
import json # <<< THÊM DÒNG NÀY
|
| 5 |
from loguru import logger
|
| 6 |
from .constants import SUMMARY_STATUS_MESSAGES, PROCESSING_STATUS_MESSAGES, FOUND_REGULATIONS_MESSAGES, BATCH_STATUS_MESSAGES
|
| 7 |
from .utils import get_random_message
|
| 8 |
from .facebook import FacebookClient
|
| 9 |
from app.config import get_settings
|
| 10 |
import re
|
|
|
|
| 11 |
|
| 12 |
class MessageProcessor:
|
| 13 |
def __init__(self, channel, sender_id):
|
|
|
|
| 180 |
conversation_context = []
|
| 181 |
total_chars = 0
|
| 182 |
|
| 183 |
+
# <<< SỬA LỖI TẠI ĐÂY >>>
|
| 184 |
+
def get_latest_timestamp(ts_value):
|
| 185 |
+
if isinstance(ts_value, (int, float)):
|
| 186 |
+
return int(ts_value)
|
| 187 |
+
if isinstance(ts_value, str):
|
| 188 |
+
try:
|
| 189 |
+
ts_value = json.loads(ts_value)
|
| 190 |
+
except (json.JSONDecodeError, TypeError):
|
| 191 |
+
try:
|
| 192 |
+
return int(ts_value)
|
| 193 |
+
except (ValueError, TypeError):
|
| 194 |
+
return 0
|
| 195 |
+
if isinstance(ts_value, list):
|
| 196 |
+
if not ts_value: return 0
|
| 197 |
+
all_timestamps = [get_latest_timestamp(item) for item in ts_value]
|
| 198 |
+
return max(all_timestamps) if all_timestamps else 0
|
| 199 |
+
return 0
|
| 200 |
+
sorted_history = sorted(history, key=lambda row: get_latest_timestamp(row.get('timestamp', 0)))
|
| 201 |
|
| 202 |
# Bước 2: Duyệt từ mới -> cũ để loại bỏ message cũ nếu cần
|
| 203 |
for row in reversed(sorted_history):
|
|
|
|
| 251 |
return
|
| 252 |
|
| 253 |
def flatten_timestamp(self, ts):
|
|
|
|
|
|
|
| 254 |
flat = []
|
| 255 |
if not isinstance(ts, list):
|
| 256 |
ts = [ts]
|
|
|
|
| 280 |
try:
|
| 281 |
reranked = await self.channel.reranker.rerank(question, matches, top_k=10)
|
| 282 |
if reranked:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
matches = reranked
|
| 284 |
except Exception as e:
|
| 285 |
logger.error(f"[RERANK] Lỗi khi rerank: {e}")
|
|
|
|
| 296 |
if not top or (match.get('similarity', 0) > top.get('similarity', 0)):
|
| 297 |
top = match
|
| 298 |
full_result_text += f"\n{(match.get('structure') or '').strip()}:\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
fullContent = (match.get('fullcontent') or '').strip()
|
| 300 |
full_result_text += f"{fullContent}"
|
| 301 |
hpbsnoidung = arr_to_str(match.get('hpbsnoidung'), sep="; ")
|
|
|
|
| 309 |
full_result_text += f"\nTạm giữ phương tiên: 07 ngày"
|
| 310 |
if top and (top.get('tieude') or top.get('noidung')):
|
| 311 |
top_result_text += f"\n{(match.get('structure') or '').strip()}:\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
fullContent = (match.get('fullcontent') or '').strip()
|
| 313 |
top_result_text += f"{fullContent}"
|
| 314 |
hpbsnoidung = arr_to_str(top.get('hpbsnoidung'), sep="; ")
|
|
|
|
| 350 |
fallback = "Tóm tắt các đoạn luật liên quan:\n\n"
|
| 351 |
for i, match in enumerate(matches, 1):
|
| 352 |
fallback += f"\n{(match.get('structure') or '').strip()}:\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
fullContent = (match.get('fullcontent') or '').strip()
|
| 354 |
fallback += f"{fullContent}"
|
| 355 |
hpbsnoidung = arr_to_str(match.get('hpbsnoidung'), sep="; ")
|
|
|
|
| 368 |
logger.info(f"[MOCK] Creating Facebook post for sender_id={sender_id} with history={history}")
|
| 369 |
return "https://facebook.com/mock_post_url"
|
| 370 |
|
|
|
|
| 371 |
async def handle_muc_phat(self, conv, conversation_context, page_token, sender_id):
|
| 372 |
vehicle = conv.get('originalvehicle', '')
|
| 373 |
action = conv.get('originalaction', '')
|
| 374 |
question = conv.get('originalquestion', '')
|
| 375 |
keywords = [kw.strip() for kw in vehicle.split(',') if kw.strip()]
|
|
|
|
|
|
|
| 376 |
if question:
|
| 377 |
logger.info(f"[DEBUG] tạo embedding: {action}")
|
| 378 |
embedding = await self.channel.embedder.create_embedding(action)
|
| 379 |
logger.info(f"[DEBUG] embedding: {embedding[:5]} ... (total {len(embedding)})")
|
|
|
|
| 380 |
from app.config import get_settings
|
| 381 |
match_count = get_settings().match_count
|
| 382 |
matches = self.channel.supabase.match_documents(
|
| 383 |
embedding,
|
| 384 |
match_count=match_count,
|
|
|
|
| 385 |
user_question=action
|
| 386 |
)
|
| 387 |
logger.info(f"[DEBUG] matches: {matches}")
|
|
|
|
| 393 |
logger.info(f"[DEBUG] Không có hành vi vi phạm: {question}")
|
| 394 |
response = "Xin lỗi, tôi không tìm thấy thông tin về hành vi vi phạm trong câu hỏi của bạn."
|
| 395 |
conv['isdone'] = True
|
|
|
|
|
|
|
|
|
|
| 396 |
return response
|
| 397 |
|
| 398 |
async def handle_quy_tac(self, conv, conversation_context, message_text):
|
| 399 |
prompt = (
|
| 400 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 401 |
f"Lịch sử:\n{conversation_context}"
|
|
|
|
| 402 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 403 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 404 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
|
|
| 411 |
prompt = (
|
| 412 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 413 |
f"Lịch sử:\n{conversation_context}"
|
|
|
|
| 414 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 415 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 416 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
|
|
| 423 |
prompt = (
|
| 424 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 425 |
f"Lịch sử:\n{conversation_context}"
|
|
|
|
| 426 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 427 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 428 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|
|
|
|
| 432 |
return answer.strip() if answer and answer.strip() else "[Đang phát triển] Tính năng trả lời về quy trình xử lý vi phạm giao thông sẽ sớm có mặt."
|
| 433 |
|
| 434 |
async def handle_ca_nhan(self, conv, conversation_context, message_text):
|
|
|
|
| 435 |
prompt = (
|
| 436 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 437 |
f"Lịch sử:\n{conversation_context}"
|
|
|
|
| 438 |
'Với các thông tin sau: "Bạn có tên là WeThoong AI, là trợ lý giao thông thông minh. Bạn được anh Viet Cat tạo ra và facebook cá nhân của anh ý là https://facebook.com/vietcat". '
|
| 439 |
'Không được trả lời bạn là AI của Google, OpenAI, hay bất kỳ hãng nào khác. '
|
| 440 |
'Hãy trả lời thông minh, hài hước, ngắn gọn cho câu hỏi sau:\n'
|
|
|
|
| 448 |
prompt = (
|
| 449 |
"Biết rằng bạn đã có lịch sử trao đổi như sau:"
|
| 450 |
f"Lịch sử:\n{conversation_context}"
|
|
|
|
| 451 |
"Bạn là một trợ lý AI có kiến thức pháp luật, hãy trả lời câu hỏi dựa trên lịch sử trao đổi"
|
| 452 |
"\n\nHãy trả lời ngắn gọn, dễ hiểu, trích dẫn rõ ràng thông tin từ các đoạn luật nếu cần."
|
| 453 |
f"\n\nCâu hỏi của người dùng: {message_text}\n"
|