File size: 20,996 Bytes
dbb6988 35f4ffd dbb6988 440a20d dbb6988 16ff3c7 5953550 a113c75 dbb6988 96d59ac 6150118 dbb6988 19142de f6c9376 44013a5 c3199eb e68c212 dbb6988 440a20d dbb6988 16ff3c7 96d59ac 16ff3c7 44013a5 16ff3c7 dbb6988 16ff3c7 dbb6988 96d59ac dbb6988 16ff3c7 dbb6988 16ff3c7 dbb6988 19142de 06dc89b 19142de 06dc89b 96d59ac 19142de 704e2f8 f6c9376 c3199eb 6723e05 c3199eb 704e2f8 16ff3c7 dbb6988 16ff3c7 dbb6988 16ff3c7 dbb6988 19142de 96d59ac dbbd289 96d59ac a113c75 96d59ac a113c75 96d59ac 16ff3c7 440a20d 16ff3c7 96d59ac dbb6988 96d59ac dbb6988 96d59ac dbb6988 96d59ac dbb6988 3c6d6b3 dbb6988 6150118 dbb6988 96d59ac dbb6988 e9365bc 611315e 96d59ac e9365bc 611315e 96d59ac dbb6988 96d59ac e68c212 4032184 e68c212 4032184 dbb6988 96d59ac dbb6988 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac 55d95bd 35f4ffd 55d95bd 96d59ac 55d95bd 96d59ac 55d95bd 96d59ac 35f4ffd 55d95bd 96d59ac 55d95bd 96d59ac 55d95bd 35f4ffd 96d59ac 55d95bd 96d59ac 35f4ffd 96d59ac 55d95bd 96d59ac 55d95bd 96d59ac 55d95bd 96d59ac 55d95bd 96d59ac 35f4ffd bd809bf 35f4ffd a9aa921 96d59ac dd9a38f 96d59ac dd9a38f 96d59ac dd9a38f 96d59ac 35f4ffd 96d59ac bd809bf 96d59ac bd809bf 35f4ffd 96d59ac 35f4ffd 96d59ac 35f4ffd 96d59ac bd809bf dd9a38f bd809bf 96d59ac bd809bf dd9a38f 96d59ac bd809bf 96d59ac dd9a38f bd809bf dd9a38f 96d59ac bd809bf 96d59ac bd809bf 96d59ac dd9a38f 96d59ac 35f4ffd 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac c3199eb 96d59ac dbb6988 96d59ac 16ff3c7 96d59ac |
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 |
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
import json
from typing import Dict, Any, List, Optional
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor
import os
import traceback
import difflib
from .config import Settings, get_settings
from .facebook import FacebookClient
from .sheets import SheetsClient
from .supabase_db import SupabaseClient
from .embedding import EmbeddingClient
from .utils import (
setup_logging,
extract_command,
extract_keywords,
timing_decorator_async,
timing_decorator_sync,
ensure_log_dir,
validate_config,
)
from .constants import VEHICLE_KEYWORDS, SHEET_RANGE, VEHICLE_KEYWORD_TO_COLUMN
from .health import router as health_router
from .llm import create_llm_client
from .reranker import Reranker
from .request_limit_manager import RequestLimitManager
from .law_document_chunker import LawDocumentChunker
from app.channel_manager import channel_manager
app = FastAPI(title="WeBot Facebook Messenger API")
# Khởi tạo version number một lần duy nhất khi server khởi động
VERSION_NUMBER = int(time.time())
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize clients
settings = get_settings()
setup_logging(settings.log_level)
logger.info("[STARTUP] Đang lấy PORT từ biến môi trường hoặc config...")
port = int(os.environ.get("PORT", settings.port if hasattr(settings, "port") else 7860))
logger.info(f"[STARTUP] PORT sử dụng: {port}")
logger.info("[STARTUP] Khởi tạo global RequestLimitManager...")
# Global RequestLimitManager instance - singleton
request_limit_manager = RequestLimitManager("gemini")
logger.info("[STARTUP] Khởi tạo FacebookClient...")
facebook_client = FacebookClient(settings.facebook_app_secret)
logger.info("[STARTUP] Khởi tạo SheetsClient...")
sheets_client = SheetsClient(
settings.google_sheets_credentials_file,
settings.google_sheets_token_file,
settings.conversation_sheet_id,
)
logger.info("[STARTUP] Khởi tạo SupabaseClient...")
supabase_client = SupabaseClient(settings.supabase_url, settings.supabase_key)
logger.info("[STARTUP] Khởi tạo EmbeddingClient...")
embedding_client = EmbeddingClient()
# Khởi tạo LLM client (ví dụ dùng HFS, bạn có thể đổi provider tuỳ ý)
# llm_client = create_llm_client(
# provider="hfs",
# base_url="https://vietcat-gemma34b.hf.space"
# )
# Khởi tạo LLM client Gemini
llm_client = create_llm_client(
provider="gemini",
base_url=settings.gemini_base_url,
model=(
settings.gemini_models_list[0]
if settings.gemini_models_list
else "gemini-2.5-flash"
),
)
reranker = Reranker() # Khởi tạo Reranker
# Khởi tạo LawDocumentChunker
law_chunker = LawDocumentChunker()
law_chunker.llm_client = llm_client
# Gán các client dùng chung cho ChannelManager.
# Đây là một bước refactor quan trọng theo nguyên tắc Dependency Injection.
# Thay vì mỗi Channel tự tạo client, chúng ta tạo một lần và chia sẻ,
# giúp tối ưu tài nguyên và làm cho code dễ quản lý, dễ test hơn.
channel_manager.set_shared_clients(
llm_client=llm_client,
sheets_client=sheets_client,
supabase_client=supabase_client,
embedding_client=embedding_client,
reranker=reranker,
)
logger.info("[STARTUP] Mount health router...")
app.include_router(health_router)
logger.info("[STARTUP] Validate config...")
validate_config(settings)
executor = ThreadPoolExecutor(max_workers=4)
message_text = None
def flatten_timestamp(ts):
flat = []
for t in ts:
if isinstance(t, list):
flat.extend(flatten_timestamp(t))
else:
flat.append(t)
return flat
def normalize_vehicle_keyword(keyword: str) -> str:
"""
Chuẩn hoá giá trị phương tiện về đúng từ khoá gần nhất trong VEHICLE_KEYWORDS.
Nếu không khớp, trả về keyword gốc.
"""
if not keyword:
return ""
matches = difflib.get_close_matches(
keyword.lower(), [k.lower() for k in VEHICLE_KEYWORDS], n=1, cutoff=0.6
)
if matches:
# Trả về đúng case trong VEHICLE_KEYWORDS
for k in VEHICLE_KEYWORDS:
if k.lower() == matches[0]:
return k
return keyword
@app.get("/")
async def root():
"""Endpoint root để kiểm tra trạng thái app."""
logger.info("[HEALTH] Truy cập endpoint root /")
return {"version": VERSION_NUMBER, "status": "ok"}
@app.get("/webhook") #
async def verify_webhook(request: Request):
"""
Xác thực webhook Facebook Messenger.
Input: request (Request) - request từ Facebook với các query params.
Output: Trả về challenge nếu verify thành công, lỗi nếu thất bại.
"""
params = dict(request.query_params)
mode = params.get("hub.mode")
token = str(params.get("hub.verify_token", ""))
challenge = str(params.get("hub.challenge", ""))
if not all([mode, token, challenge]):
raise HTTPException(status_code=400, detail="Missing parameters")
return await facebook_client.verify_webhook(
token, challenge, settings.facebook_verify_token
)
@app.post("/webhook")
@timing_decorator_async
async def webhook(request: Request):
"""
Nhận và xử lý message từ Facebook Messenger webhook.
Input: request (Request) - request chứa payload JSON từ Facebook.
Output: JSON status.
"""
logger.info(f"[DEBUG] Nhận message từ Facebook Messenger webhook...")
body_bytes = await request.body()
# Verify request is from Facebook
if not facebook_client.verify_signature(request, body_bytes):
raise HTTPException(status_code=403, detail="Invalid signature")
try:
body = json.loads(body_bytes)
# Kiểm tra an toàn echo
is_echo = (
isinstance(body, dict)
and "entry" in body
and isinstance(body["entry"], list)
and len(body["entry"]) > 0
and "messaging" in body["entry"][0]
and isinstance(body["entry"][0]["messaging"], list)
and len(body["entry"][0]["messaging"]) > 0
and body["entry"][0]["messaging"][0]
.get("message", {})
.get("is_echo", False)
)
if is_echo:
logger.info(f"[DEBUG] Message is echo, skipping...")
return {"status": "ok"}
else:
message_data = facebook_client.parse_message(body)
logger.info(f"[DEBUG] message_data: {message_data}")
if not message_data:
return {"status": "ok"}
# --- Refactor: Lấy page_id, sender_id, channel, conversation, gọi message_processor --- # noqa
page_id = message_data.get("page_id")
sender_id = message_data.get("sender_id")
channel = channel_manager.get_or_create_channel("facebook", page_id)
conversation = channel.get_or_create_conversation(sender_id)
await conversation.process_message(message_data)
return {"status": "ok"}
except Exception as e:
logger.error(
f"Error processing webhook: {e}\nTraceback: {traceback.format_exc()}"
)
raise HTTPException(status_code=500, detail="Internal server error")
# ==================== DOCUMENT CHUNK MANAGEMENT APIs ====================
@app.delete("/api/document-chunks/clear")
@timing_decorator_async
async def delete_all_document_chunks():
"""
API xóa toàn bộ bảng document_chunks.
"""
try:
logger.info("[API] Starting delete all document chunks")
success = supabase_client.delete_all_document_chunks()
if success:
logger.info("[API] Successfully deleted all document chunks")
return {"status": "success", "message": "Đã xóa toàn bộ document chunks"}
else:
logger.error("[API] Failed to delete all document chunks")
raise HTTPException(status_code=500, detail="Lỗi khi xóa document chunks")
except Exception as e:
logger.error(f"[API] Error in delete_all_document_chunks: {e}")
raise HTTPException(status_code=500, detail=f"Lỗi: {str(e)}")
@app.post("/api/document-chunks/update")
@timing_decorator_async
async def update_specific_document(file_name: str, document_id: int):
"""
API cập nhật file xác định trong thư mục data.
Args:
file_name: Tên file trong thư mục data (ví dụ: "luat_giao_thong.txt")
document_id: ID văn bản luật
"""
try:
logger.info(
f"[API] Starting update specific document: {file_name}, document_id: {document_id}"
)
# Kiểm tra file tồn tại
file_path = f"data/{file_name}"
if not os.path.exists(file_path):
logger.error(f"[API] File not found: {file_path}")
raise HTTPException(
status_code=404, detail=f"File không tồn tại: {file_name}"
)
# Xóa chunks cũ của document_id này (nếu có)
logger.info(f"[API] Deleting old chunks for document_id: {document_id}")
supabase_client.delete_document_chunks_by_vanbanid(document_id)
# Xử lý văn bản mới
logger.info(f"[API] Processing document: {file_path}")
success = await law_chunker.process_law_document(file_path, document_id)
if success:
logger.info(f"[API] Successfully updated document: {file_name}")
return {
"status": "success",
"message": f"Đã cập nhật thành công văn bản: {file_name}",
"document_id": document_id,
"file_name": file_name,
}
else:
logger.error(f"[API] Failed to update document: {file_name}")
raise HTTPException(
status_code=500, detail=f"Lỗi khi xử lý văn bản: {file_name}"
)
except HTTPException:
raise
except Exception as e:
logger.error(f"[API] Error in update_specific_document: {e}")
raise HTTPException(status_code=500, detail=f"Lỗi: {str(e)}")
@app.post("/api/document-chunks/update-all")
@timing_decorator_async
async def update_all_documents():
"""
API cập nhật tự động toàn bộ file trong thư mục data.
"""
try:
logger.info("[API] Starting update all documents")
# Kiểm tra thư mục data tồn tại
data_dir = "data"
if not os.path.exists(data_dir):
logger.warning(f"[API] Data directory not found: {data_dir}")
return {
"status": "warning",
"message": "Thư mục data không tồn tại",
"processed_files": [],
"failed_files": [],
}
# Lấy danh sách file .txt trong thư mục data
txt_files = [f for f in os.listdir(data_dir) if f.endswith(".txt")]
if not txt_files:
logger.warning("[API] No .txt files found in data directory")
return {
"status": "warning",
"message": "Không tìm thấy file .txt nào trong thư mục data",
"processed_files": [],
"failed_files": [],
}
logger.info(f"[API] Found {len(txt_files)} .txt files to process")
processed_files = []
failed_files = []
# Xử lý từng file
for i, file_name in enumerate(txt_files, 1):
try:
logger.info(f"[API] Processing file {i}/{len(txt_files)}: {file_name}")
# Sử dụng index làm document_id (có thể thay đổi logic này)
document_id = i
# Xóa chunks cũ của document_id này (nếu có)
supabase_client.delete_document_chunks_by_vanbanid(document_id)
# Xử lý văn bản
file_path = os.path.join(data_dir, file_name)
success = await law_chunker.process_law_document(file_path, document_id)
if success:
processed_files.append(
{
"file_name": file_name,
"document_id": document_id,
"status": "success",
}
)
logger.info(f"[API] Successfully processed: {file_name}")
else:
failed_files.append(
{
"file_name": file_name,
"document_id": document_id,
"status": "failed",
"error": "Processing failed",
}
)
logger.error(f"[API] Failed to process: {file_name}")
except Exception as e:
logger.error(f"[API] Error processing {file_name}: {e}")
failed_files.append(
{
"file_name": file_name,
"document_id": i,
"status": "failed",
"error": str(e),
}
)
# Tổng kết
total_files = len(txt_files)
success_count = len(processed_files)
failed_count = len(failed_files)
logger.info(
f"[API] Update all completed: {success_count}/{total_files} files processed successfully"
)
return {
"status": "success",
"message": f"Đã xử lý {success_count}/{total_files} files thành công",
"total_files": total_files,
"processed_files": processed_files,
"failed_files": failed_files,
}
except Exception as e:
logger.error(f"[API] Error in update_all_documents: {e}")
raise HTTPException(status_code=500, detail=f"Lỗi: {str(e)}")
@app.get("/api/document-chunks/view")
@timing_decorator_async
async def view_all_document_chunks():
"""
API xem toàn bộ dữ liệu trong bảng document_chunks theo cấu trúc cây.
"""
try:
logger.info("[API] Starting view all document chunks")
# Lấy dữ liệu từ Supabase
chunks_data = supabase_client.get_all_document_chunks()
# Thống kê cơ bản
total_chunks = len(chunks_data)
unique_documents = len(
set(chunk.get("vanbanid") for chunk in chunks_data if chunk.get("vanbanid"))
)
# Nhóm theo vanbanid
chunks_by_document = {}
for chunk in chunks_data:
vanbanid = chunk.get("vanbanid")
if vanbanid not in chunks_by_document:
chunks_by_document[vanbanid] = []
chunks_by_document[vanbanid].append(chunk)
# Thống kê chi tiết
document_stats = []
hierarchical_data = []
for vanbanid, chunks in chunks_by_document.items():
# Thống kê
document_stats.append(
{
"vanbanid": vanbanid,
"chunk_count": len(chunks),
"document_title": (
chunks[0].get("document_title", "Unknown")
if chunks
else "Unknown"
),
}
)
# Tạo cấu trúc cây cho từng văn bản
tree_structure = build_chunk_tree(chunks)
hierarchical_data.append(
{
"vanbanid": vanbanid,
"document_title": (
chunks[0].get("document_title", "Unknown")
if chunks
else "Unknown"
),
"chunk_count": len(chunks),
"chunks": tree_structure,
}
)
return {
"status": "success",
"message": f"Đã lấy {total_chunks} chunks từ {unique_documents} văn bản",
"summary": {
"total_chunks": total_chunks,
"unique_documents": unique_documents,
"document_stats": document_stats,
},
"data": hierarchical_data,
}
except Exception as e:
logger.error(f"[API] Error in view_all_document_chunks: {e}")
raise HTTPException(status_code=500, detail=f"Lỗi: {str(e)}")
def build_chunk_tree(chunks: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Xây dựng cấu trúc cây từ danh sách chunks phẳng.
Cách đơn giản: tìm root nodes (cha=None) trước, sau đó tìm children.
"""
if not chunks:
return []
# Debug: Kiểm tra tất cả chunks
root_count = 0
child_count = 0
for chunk in chunks:
if chunk.get("cha") is None:
root_count += 1
logger.debug(f"[TREE] Root chunk: {chunk.get('content', '')[:100]}") # noqa
else:
child_count += 1
logger.debug(
f"[TREE] Child chunk: {chunk.get('content', '')[:100]} -> parent: {chunk.get('cha')}"
) # noqa
logger.info(
f"[TREE] Found {root_count} root chunks and {child_count} child chunks from {len(chunks)} total chunks"
)
# Tạo dictionary để truy cập nhanh
chunks_dict = {chunk["id"]: chunk for chunk in chunks}
def build_node(chunk_id: str) -> Dict[str, Any]:
"""Tạo node và tìm tất cả children của nó."""
chunk = chunks_dict[chunk_id]
# Tạo node
node = {
"id": chunk_id,
"content": chunk.get("content", ""),
"vanbanid": chunk.get("vanbanid"),
"cha": chunk.get("cha"),
"document_title": chunk.get("document_title", ""),
"article_number": chunk.get("article_number"),
"article_title": chunk.get("article_title", ""),
"clause_number": chunk.get("clause_number", ""),
"sub_clause_letter": chunk.get("sub_clause_letter", ""),
"context_summary": chunk.get("context_summary", ""),
"data": chunk, # Toàn bộ dữ liệu gốc
"children": [],
}
# Tìm tất cả children của node này
children_count = 0
for other_chunk in chunks:
if other_chunk.get("cha") == chunk_id:
child_node = build_node(other_chunk["id"])
node["children"].append(child_node)
children_count += 1
logger.debug(
f"[TREE] Node {chunk_id[:8]}... has {children_count} children"
) # noqa
return node
# Tìm tất cả root nodes (cha=None) và sắp xếp theo thứ tự xuất hiện
root_chunks = []
processed_ids = set() # Để tránh xử lý trùng lặp
for chunk in chunks:
if chunk.get("cha") is None and chunk["id"] not in processed_ids:
root_node = build_node(chunk["id"])
root_chunks.append(root_node)
processed_ids.add(chunk["id"])
logger.info(f"[TREE] Added root node: {chunk.get('content', '')[:100]}")
logger.info(
f"[TREE] Built tree with {len(root_chunks)} root nodes from {len(chunks)} total chunks"
)
logger.info(
f"[TREE] Root chunks: {[chunk.get('content', '')[:50] for chunk in root_chunks]}"
)
return root_chunks
@app.get("/api/document-chunks/status")
@timing_decorator_async
async def get_document_chunks_status():
"""
API lấy thông tin trạng thái của document chunks.
"""
try:
logger.info("[API] Getting document chunks status")
# Lấy thống kê từ Supabase
# Note: Cần implement method này trong SupabaseClient nếu cần
# Kiểm tra thư mục data
data_dir = "data"
txt_files = []
if os.path.exists(data_dir):
txt_files = [f for f in os.listdir(data_dir) if f.endswith(".txt")]
return {
"status": "success",
"data_directory": data_dir,
"available_files": txt_files,
"file_count": len(txt_files),
"message": f"Tìm thấy {len(txt_files)} file .txt trong thư mục data",
}
except Exception as e:
logger.error(f"[API] Error in get_document_chunks_status: {e}")
raise HTTPException(status_code=500, detail=f"Lỗi: {str(e)}")
if __name__ == "__main__":
import uvicorn
logger.info("[STARTUP] Bắt đầu chạy uvicorn server...")
uvicorn.run("app.main:app", host="0.0.0.0", port=port)
|