civic-backup / src /generation /answer_composer.py
khiemdztv's picture
Backup source code and docs
cf29045 verified
Raw History Blame Contribute Delete
14.1 kB
"""Dựng câu trả lời có cấu trúc từ các ý ĐÃ được kiểm chứng.
Bố cục (giống cách một chuyên viên pháp lý trả lời):
1. Kết luận trực tiếp
2. Quy định liên quan (các ý có trích dẫn nguyên văn)
3. Thành phần hồ sơ theo thủ tục (chép nguyên văn từ TTHC, không qua LLM)
4. Bạn nên làm gì tiếp theo (văn mẫu theo intent, configs/answer_style.yaml)
5. Tôi có thể hỗ trợ thêm (văn mẫu theo intent)
6. Căn cứ tham khảo
Chỉ mục 1–3 mang nội dung pháp lý, và mọi chữ ở đó hoặc có quote nguyên văn đã
kiểm, hoặc chép thẳng từ nguồn. Mục 4–5 là văn mẫu do cán bộ nghiệp vụ duyệt,
không chứa số hiệu văn bản (test chặn điều đó).
"""
from __future__ import annotations
import re
from functools import lru_cache
from typing import Any, Dict, List, Optional, Sequence, Tuple
from ..common.config import load_config
HOSO_SECTION = "THÀNH PHẦN HỒ SƠ"
STEPS_SECTION = "TRÌNH TỰ THỰC HIỆN"
_SPACE = re.compile(r"\s+")
_WORD = re.compile(r"[0-9a-zA-ZÀ-ỹà-ỹ]+")
_HEADER = re.compile(r"^\[[^\]]*\]\s*$")
# Chỉ mục BM25 lưu text đã gộp khoảng trắng (mất xuống dòng): tiêu đề "[Thủ tục … > MỤC]"
# dính liền nội dung và các mốc "## Trường hợp"/"## Bước" nằm giữa dòng.
_HEADER_INLINE = re.compile(r"^\s*\[[^\]\n]*\]\s*")
_MARK = re.compile(r"[ \t]*(##\s)")
_CASE = re.compile(r"^##\s*Trường hợp\s*\d+\s*:\s*(.*)$")
_STEP = re.compile(r"^##\s*Bước\s*\d+\s*:\s*(.*)$")
_TABLE_HEAD = re.compile(r"Tên giấy tờ\s+Mẫu đơn, tờ khai\s+Số lượng\s*", re.I)
_SUBCASE = re.compile(r"((?:Trường hợp|Đối với)[^.:]{0,250}?ngoài (?:các )?giấy tờ[^:]{0,200}:)")
_TAIL_JUNK = re.compile(r"\s*Hình thức nộp\b.*$", re.S)
_QTY = re.compile(r"\b\d+\s+bản\s+(?:chính|sao)\b", re.I)
# Tên file biểu mẫu đính kèm ("...; Giấy ĐN đăng ký hộ kd.docx", "... TT-BTC. Mẫu số 2.docx").
_FILE = re.compile(r"(?<=[.;])\s*[^.;()]{0,60}\.(?:docx?|pdf|xlsx?)\b", re.I)
_FILE_EXT = re.compile(r"\.(?:docx?|pdf|xlsx?)\b", re.I)
_BULLET = re.compile(r"^(?:[-–•*]\s*|\([ivx]+\)\s*|[a-zđ]\)\s*)", re.I)
_DOC_STOP = {"và", "hoặc", "của", "các", "giấy", "bản", "sao", "chính", "theo", "cho",
"có", "phải", "đối", "với", "trường", "hợp"}
def _compact(text: str) -> str:
return _SPACE.sub(" ", text or "").strip()
@lru_cache(maxsize=1)
def style() -> Dict[str, Any]:
try:
return dict(load_config("answer_style"))
except Exception: # pragma: no cover
return {}
# ------------------------------------------------------------ hồ sơ parsing
def merge_section_chunks(texts: Sequence[str]) -> str:
"""Nối các chunk liên tiếp của cùng một mục, bỏ đoạn gối đầu giữa hai chunk (nếu có).
Đoạn gối đầu được nhận diện bằng >= 6 từ cuối của chunk trước xuất hiện ở ĐẦU
chunk sau (cho phép khác khoảng trắng/xuống dòng). Giữ nguyên xuống dòng của nguồn.
"""
merged = ""
for raw in texts:
body = _HEADER_INLINE.sub("", raw or "").strip()
if not merged:
merged = body
continue
words = merged.split()
for k in range(min(14, len(words)), 5, -1):
tail = words[-k:]
if len(" ".join(tail)) < 30:
break
m = re.search(r"\s+".join(map(re.escape, tail)), body[:600 + len(" ".join(tail))])
if m:
body = body[m.end():].lstrip(" ")
break
merged = merged + "\n" + body
return merged
def _clip(text: str, limit: int = 240) -> str:
"""Rút gọn mục quá dài tại ranh giới từ; dấu … báo rằng nguồn còn tiếp."""
if len(text) <= limit:
return text
return text[:limit].rsplit(" ", 1)[0].rstrip(" ,;:-") + "…"
def parse_document_items(text: str) -> List[Dict[str, Any]]:
"""Tách mục THÀNH PHẦN HỒ SƠ thành các trường hợp, mỗi trường hợp là danh sách giấy tờ.
Chỉ cắt/ghép chữ có sẵn trong nguồn, không viết lại.
"""
cases: List[Dict[str, Any]] = []
current: Dict[str, Any] = {"header": "", "lines": []}
text = _MARK.sub(r"\n\1", _HEADER_INLINE.sub("", text or ""))
for line in text.splitlines():
s = line.strip()
if not s or _HEADER.match(s):
continue
m = _CASE.match(s)
if m:
if current["lines"] or current["header"]:
cases.append(current)
rest = m.group(1)
# Text đã gộp: tiêu đề và bảng giấy tờ chung một dòng; bảng bắt đầu ở "Tên giấy tờ".
table = _TABLE_HEAD.search(rest)
header, body = (rest[:table.start()], [rest[table.start():]]) if table else (rest, [])
current = {"header": _compact(header), "lines": body}
continue
current["lines"].append(s)
if current["lines"] or current["header"]:
cases.append(current)
# Một số thủ tục mở trường hợp mới giữa đoạn, không có tiêu đề "## Trường hợp".
split_cases: List[Dict[str, Any]] = []
for case in cases:
parts = _SUBCASE.split(_TAIL_JUNK.sub("", " ".join(case["lines"])))
split_cases.append({"header": case["header"], "body": parts[0]})
for i in range(1, len(parts) - 1, 2):
split_cases.append({"header": _compact(parts[i]), "body": parts[i + 1]})
out: List[Dict[str, Any]] = []
for case in split_cases:
body = _TABLE_HEAD.sub("\n", case["body"])
items: List[str] = []
raw_items: List[str] = []
for seg in _QTY.split(body):
seg = _compact(_FILE_EXT.sub("", _FILE.sub("", seg)))
seg = _compact(_BULLET.sub("", seg)).strip(" ;,-")
if raw_items and seg[:1].islower():
# Ô "số lượng" của bảng PDF chen giữa một từ ("kin | h tế"): nối lại.
raw_items[-1] += seg
elif len(seg) >= 10:
raw_items.append(seg)
for seg in raw_items:
seg = _clip(re.sub(r"(?:\s+\d+)+$", "", seg).rstrip(" ."))
if seg not in items:
items.append(seg)
header = re.sub(r"^\*\s*", "", case["header"]).strip(" :*-")
out.append({"header": header, "items": items})
return [c for c in out if c["items"]]
def parse_steps(text: str) -> List[str]:
"""Các bước "## Bước N: ..." của mục TRÌNH TỰ THỰC HIỆN, giữ nguyên chữ nguồn."""
steps: List[str] = []
for line in _MARK.sub(r"\n\1", _HEADER_INLINE.sub("", text or "")).splitlines():
m = _STEP.match(line.strip())
if m:
# Chỉ giữ câu chính của bước; các ý phụ "- Trường hợp …" xem tại nguồn.
step = _clip(re.split(r"\s+-\s+", _compact(m.group(1)))[0].rstrip(" :"), 300)
if len(step) >= 8 and step not in steps:
steps.append(step)
return steps
def _doc_words(text: str) -> set:
return {w.lower() for w in _WORD.findall(text or "")
if len(w) > 1 and w.lower() not in _DOC_STOP}
def documents_not_listed(asked: Sequence[str], hoso_text: str,
min_overlap: float = 0.6) -> List[str]:
"""Giấy tờ công dân nêu mà KHÔNG xuất hiện trong thành phần hồ sơ đã công bố."""
have = _doc_words(hoso_text)
missing: List[str] = []
for doc in asked:
words = _doc_words(doc)
if not words:
continue
if len(words & have) / len(words) < min_overlap and doc not in missing:
missing.append(doc)
return missing
def validate_asked_documents(raw: Any, question: str) -> List[str]:
"""LLM chỉ được CHÉP tên giấy tờ có sẵn trong câu hỏi, không được tự nghĩ ra."""
if not isinstance(raw, list):
return []
q = _compact(question).lower()
out: List[str] = []
for item in raw[:4]:
doc = _compact(str(item or ""))
if 6 <= len(doc) <= 120 and doc.lower() in q and doc not in out:
out.append(doc)
return out
# ------------------------------------------------------------ composition
def _join_vn(names: Sequence[str]) -> str:
names = [f"“{n}”" for n in names]
return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " và " + names[-1]
def _lines_for(key: str, intent: str) -> List[str]:
table = style().get(key) or {}
return list(table.get(intent) or table.get("DEFAULT") or [])
def compose(points: Sequence[str], payload: Dict[str, Any], used: Sequence[int],
not_listed: Sequence[str] = ()) -> Tuple[str, List[int]]:
"""points: các câu đã kiểm, đã gắn [n]. used: id nguồn (1-based) đã dùng.
Trả (câu trả lời, danh sách id nguồn thực sự xuất hiện trong câu trả lời).
"""
evidence = payload.get("verified_evidence") or []
state = payload.get("state") or {}
intent = state.get("intent") or "OTHER"
question = (payload.get("user_query") or "").lower()
hoso = payload.get("procedure_documents") or {}
hoso_id = hoso.get("source")
used = list(used)
sections: List[str] = []
steps_info = payload.get("procedure_steps") or {}
steps_id = steps_info.get("source")
# Ý nào chỉ nhắc lại mục hồ sơ/trình tự thì bỏ: các mục đó được hiển thị nguyên văn bên dưới.
listed = {i for i in (hoso_id, steps_id) if i}
remaining = [p for p in points if not any(p.endswith(f"[{i}].") for i in listed)] or list(points[:1])
if not_listed and hoso_id:
conclusion = [
f"Theo thành phần hồ sơ của thủ tục “{hoso.get('title', '')}” đang được công bố "
f"[{hoso_id}], {_join_vn(not_listed)} không thuộc danh sách giấy tờ phải nộp."]
if re.search(r"\b(?:yêu cầu|bắt|đòi|buộc)\b", question):
conclusion.append(style().get("extra_document_rule", ""))
sections.append(" ".join(c for c in conclusion if c))
if hoso_id not in used:
used.append(hoso_id)
elif remaining:
sections.append(remaining.pop(0))
elif hoso_id or steps_id:
# Không có ý LLM nào qua kiểm chứng: chỉ nêu tên thủ tục đã tra được, không kết luận.
ref = steps_id or hoso_id
title = (steps_info or hoso).get("title", "")
sections.append(f"Thủ tục liên quan tra cứu được là “{title}” [{ref}]. "
"Nội dung dưới đây chép từ thủ tục đang được công bố.")
if ref not in used:
used.append(ref)
if remaining:
sections.append("Quy định liên quan:\n" + "\n".join(f"- {p}" for p in remaining))
show_docs = hoso_id and (not_listed or intent in set(style().get("show_documents_for", []))
or any(k in question for k in ("hồ sơ", "giấy tờ", "cần gì")))
if show_docs:
cases = parse_document_items(hoso.get("text", ""))
if cases:
max_items = int(style().get("max_document_items", 8))
lines = [f"Thành phần hồ sơ theo quy định [{hoso_id}]:"]
lines += [f"- {item}" for item in cases[0]["items"][:max_items]]
others = [c["header"] for c in cases[1:] if c["header"]]
if others:
lines.append(f"Ngoài ra còn {len(others)} trường hợp khác; "
f"xem chi tiết tại nguồn [{hoso_id}].")
sections.append("\n".join(lines))
if hoso_id not in used:
used.append(hoso_id)
show_steps = steps_id and intent in set(style().get("show_steps_for", []))
if show_steps:
steps = parse_steps(steps_info.get("text", ""))
if steps:
max_steps = int(style().get("max_steps", 6))
sections.append(f"Trình tự thực hiện [{steps_id}]:\n" + "\n".join(
f"{i}. {step}" for i, step in enumerate(steps[:max_steps], 1)))
if steps_id not in used:
used.append(steps_id)
missing = payload.get("missing_slots") or []
if missing:
from .template_verbalizer import _slot_phrase
sections.append(f"Để hướng dẫn chính xác hơn, bạn cho biết thêm {_slot_phrase(missing)}.")
if payload.get("system_response"):
sections.append(f"Hướng xử lý: {payload['system_response']}")
steps = _lines_for("next_steps", "EXTRA_DOCUMENT" if not_listed else intent)
if steps:
sections.append("Bạn nên làm gì tiếp theo:\n" + "\n".join(f"- {s}" for s in steps))
offers = _lines_for("offers", "EXTRA_DOCUMENT" if not_listed else intent)
if offers:
sections.append("Nếu cần, tôi có thể hỗ trợ bạn:\n" + "\n".join(f"- {s}" for s in offers))
from .template_verbalizer import _citation_label
used = [i for i in used if 1 <= i <= len(evidence)]
refs = [f"[{i}] {_citation_label(evidence[i - 1])}" for i in sorted(used)]
if refs:
sections.append("Căn cứ tham khảo:\n" + "\n".join(refs))
return "\n\n".join(sections), used
def build_procedure_section(evidence: Sequence[Any], section: str) -> Optional[Dict[str, Any]]:
"""Tìm một mục TTHC (đã ghép đủ) trong evidence đã kiểm; source là id 1-based."""
for idx, ev in enumerate(evidence, 1):
if ev.source == "tthc" and ev.section == section and ev.text:
return {"source": idx, "title": ev.title, "text": ev.text}
return None
def build_procedure_documents(evidence: Sequence[Any]) -> Optional[Dict[str, Any]]:
return build_procedure_section(evidence, HOSO_SECTION)