"""API FastAPI (tuỳ chọn, ngoài Definition of Done). uvicorn src.inference.server:app --host 0.0.0.0 --port 8000 """ from __future__ import annotations import os from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel, Field from ..common.config import load_config, load_env_file from ..common.logging_utils import get_logger from .pipeline import CivicPipeline LOG = get_logger("server") app = FastAPI(title="Civic AI", version="1.0", description="Trợ lý hỗ trợ xử lý phản ánh, kiến nghị của người dân") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) _PIPE: Optional[CivicPipeline] = None class HistoryTurn(BaseModel): query: str = Field(..., max_length=8000, description="Câu hỏi của lượt trước") standalone_query: Optional[str] = Field( None, max_length=8000, description="Câu hỏi đầy đủ máy chủ đã hiểu ở lượt đó") known_slots: Optional[Dict[str, str]] = Field( None, description="known_slots máy chủ trả về ở lượt đó") class AnalyzeRequest(BaseModel): query: str = Field(..., min_length=5, max_length=8000, description="Nội dung phản ánh của công dân") date: Optional[str] = Field(None, description="Ngày truy vấn YYYY-MM-DD") trace: bool = False slots: Optional[Dict[str, str]] = Field( None, description="Thông tin người dân nhập trên form, ví dụ " '{"application_id": "...", "procedure_name": "..."}') history: Optional[List[HistoryTurn]] = Field( None, max_length=10, description="Các lượt trước trong cùng phiên (trình duyệt giữ; máy chủ không lưu)") @app.on_event("startup") def _startup() -> None: global _PIPE loaded = load_env_file() if loaded: LOG.info("Đã nạp .env: %s", ", ".join(loaded)) # chỉ tên biến, không in giá trị cfg = load_config("civic_nlu") _PIPE = CivicPipeline( cfg, device=os.environ.get("CIVIC_DEVICE", "cpu"), backend=os.environ.get("CIVIC_BACKEND", "torch"), use_retrieval=os.environ.get("CIVIC_RETRIEVAL", "1") == "1", ) LOG.info("Pipeline sẵn sàng.") _STATIC = Path(__file__).parent / "static" @app.get("/", include_in_schema=False) def index() -> FileResponse: """Giao diện gửi phản ánh — gọi /v1/civic/analyze cùng origin.""" return FileResponse(_STATIC / "index.html") @app.get("/healthz") def healthz() -> Dict[str, Any]: reasoner = getattr(_PIPE, "reasoner", None) return {"status": "ok", "model_loaded": _PIPE is not None, "reasoner": reasoner.model if reasoner is not None else None} @app.post("/v1/civic/analyze") def analyze(req: AnalyzeRequest) -> Dict[str, Any]: if _PIPE is None: raise HTTPException(503, "Pipeline chưa sẵn sàng") try: history = [t.model_dump() for t in req.history] if req.history else None resp = _PIPE.run(req.query, req.date, trace=req.trace, form_slots=req.slots, history=history) except Exception as e: # pragma: no cover LOG.exception("Lỗi xử lý") raise HTTPException(500, str(e)[:300]) return resp.to_dict(include_trace=req.trace) class KnowledgeQueryRequest(BaseModel): query: str = Field(..., description="Từ khóa tra cứu") limit: Optional[int] = Field(15, ge=1, le=50, description="Số lượng kết quả tối đa") @app.get("/v1/civic/knowledge/tthc") @app.post("/v1/civic/knowledge/tthc") def search_tthc(q: Optional[str] = None, limit: int = 15, body: Optional[KnowledgeQueryRequest] = None) -> Dict[str, Any]: """Tra cứu cơ sở dữ liệu Thủ tục hành chính (TTHC).""" if _PIPE is None: raise HTTPException(503, "Pipeline chưa sẵn sàng") query_text = (body.query if body else q or "").strip() if not query_text: return {"status": "ok", "query": "", "total": 0, "results": []} lim = body.limit if (body and body.limit) else limit r = _PIPE.retriever() if r is None: return {"status": "error", "message": "Retriever chưa được khởi tạo", "results": []} raw_items = r.search_route(query_text, "tthc", mode="bm25") seen_docs = set() results = [] for it in raw_items: doc_key = it.doc_id or it.title if doc_key in seen_docs: continue seen_docs.add(doc_key) results.append({ "doc_id": it.doc_id or "", "title": it.title or "Thủ tục hành chính", "section": it.section or "", "breadcrumb": it.breadcrumb or "", "co_quan_ban_hanh": it.co_quan_ban_hanh or "Cơ quan hành chính nhà nước", "url": it.url or "https://dichvucong.gov.vn/tra-cuu-thu-tuc/danh-sach", "snippet": it.text[:400] + ("..." if len(it.text) > 400 else ""), "full_text": it.text, "score": round(float(it.rrf_score), 4), }) if len(results) >= lim: break return {"status": "ok", "query": query_text, "total": len(results), "results": results} @app.get("/v1/civic/knowledge/vbpl") @app.post("/v1/civic/knowledge/vbpl") def search_vbpl(q: Optional[str] = None, limit: int = 15, body: Optional[KnowledgeQueryRequest] = None) -> Dict[str, Any]: """Tra cứu cơ sở dữ liệu Văn bản quy phạm pháp luật (VBPL).""" if _PIPE is None: raise HTTPException(503, "Pipeline chưa sẵn sàng") query_text = (body.query if body else q or "").strip() if not query_text: return {"status": "ok", "query": "", "total": 0, "results": []} lim = body.limit if (body and body.limit) else limit r = _PIPE.retriever() if r is None: return {"status": "error", "message": "Retriever chưa được khởi tạo", "results": []} raw_items = r.search_route(query_text, "vbpl", mode="bm25") results = [] for it in raw_items[:lim]: doc_url = it.url or (f"https://vbpl.vn/van-ban/chi-tiet/{it.doc_id}" if it.doc_id else "https://vbpl.vn") results.append({ "doc_id": it.doc_id or "", "so_hieu": it.so_hieu or "Văn bản pháp luật", "title": it.title or "Văn bản quy phạm pháp luật", "section": it.section or "", "breadcrumb": it.breadcrumb or "", "co_quan_ban_hanh": it.co_quan_ban_hanh or "Cơ quan có thẩm quyền", "ngay_hieu_luc": it.ngay_hieu_luc or "", "con_hieu_luc": it.con_hieu_luc if it.con_hieu_luc is not None else True, "url": doc_url, "snippet": it.text[:400] + ("..." if len(it.text) > 400 else ""), "full_text": it.text, "score": round(float(it.rrf_score), 4), }) return {"status": "ok", "query": query_text, "total": len(results), "results": results}