File size: 7,409 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lệnh thực thi duy nhất — final.md PHẦN V.6.

    python -m src.inference.cli                                  # chế độ hỏi–đáp liên tục
    python -m src.inference.cli --query "Tôi nộp hồ sơ ..."      # chạy một câu rồi thoát
    python -m src.inference.cli --query "..." --no-retrieval --trace   # nhánh < 100 ms
"""
from __future__ import annotations

import argparse
import json
import sys
from typing import Any, Dict, List

from ..common.config import add_config_args, load_config, load_env_file
from ..common.logging_utils import get_logger
from .pipeline import CivicPipeline

LOG = get_logger("cli")

BANNER = """
==============================================================
  CIVIC AI — Trợ lý xử lý Phản ánh, Kiến nghị của người dân
==============================================================
  Dán nội dung phản ánh (nhiều dòng được), rồi Enter 2 lần để gửi.
  Lệnh:  /json  bật-tắt xem JSON đầy đủ
         /trace bật-tắt xem độ trễ từng khối
         /thoat kết thúc   (hoặc Ctrl-D)
"""

_LABEL_W = 22


def _row(label: str, value: str) -> str:
    return f"  {label:<{_LABEL_W}}{value}"


def render_human(d: Dict[str, Any]) -> str:
    """In gọn cho người đọc. JSON đầy đủ vẫn lấy được bằng /json."""
    conf = d.get("confidence") or {}
    out: List[str] = ["", "-" * 62]

    def with_conf(key: str, ckey: str) -> str:
        v = d.get(key) or "—"
        c = conf.get(ckey)
        return f"{v}" + (f"   ({c:.2f})" if isinstance(c, (int, float)) else "")

    out.append(_row("Lĩnh vực", with_conf("domain", "domain")))
    out.append(_row("Ý định", with_conf("intent", "intent")))
    out.append(_row("Vấn đề", with_conf("problem_type", "problem")))

    known = d.get("known_slots") or {}
    out.append(_row("Thông tin đã có",
                    ", ".join(f"{k}={v}" for k, v in known.items()) if known else "—"))
    missing = d.get("missing_slots") or []
    out.append(_row("Còn thiếu", ", ".join(missing) if missing else "—"))
    out.append(_row("Hành động", with_conf("next_action", "action")))

    routes = d.get("retrieval_routes") or []
    out.append(_row("Tra cứu", ", ".join(routes) if routes else "—"))

    ok = "CÓ" if d.get("can_answer_directly") else "KHÔNG"
    rc = d.get("reason_code")
    out.append(_row("Trả lời thẳng được?", ok + (f"   [{rc}]" if rc else "")))

    out.append("")
    out.append("  ── Nội dung trả lời ──")
    for line in (d.get("answer") or "(trống)").split("\n"):
        out.append(f"  {line}" if line else "")

    ev = d.get("evidence") or []
    if ev:
        out.append("  ── Căn cứ pháp lý ──")
        for i, e in enumerate(ev, 1):
            verdict = e.get("verdict")
            tail = f"   [{verdict}]" if verdict else ""
            out.append(f"  [{i}] {e.get('citation') or e.get('title') or e.get('chunk_id')}"
                       f"   (điểm {e.get('score')}){tail}")
            if e.get("url"):
                out.append(f"      {e['url']}")
    elif d.get("citations"):
        out.append("  ── Căn cứ pháp lý ──")
        for i, c in enumerate(d["citations"], 1):
            out.append(f"  [{i}] {c}")

    tr = d.get("trace") or {}
    if tr.get("latency_ms"):
        marks = "  ".join(f"{k} {v:.0f}ms" for k, v in tr["latency_ms"].items())
        out.append("")
        out.append(_row("Độ trễ", f"{marks}   | tổng {tr.get('total_ms', 0):.0f}ms"))

    out.append("-" * 62)
    return "\n".join(out)


def read_block(prompt: str) -> str | None:
    """Đọc nhiều dòng tới khi gặp dòng trống. None = kết thúc phiên."""
    lines: List[str] = []
    while True:
        try:
            line = input(prompt if not lines else "  ... ")
        except (EOFError, KeyboardInterrupt):
            return None
        if line.strip() == "":
            if lines:
                return "\n".join(lines)
            continue
        lines.append(line)


def interactive(pipe: CivicPipeline, args) -> int:
    print(BANNER)
    show_json, show_trace = bool(args.json_only), bool(args.trace)
    while True:
        query = read_block("\nPhản ánh> ")
        if query is None:
            print("\nKết thúc phiên.")
            return 0
        cmd = query.strip().lower()
        if cmd in ("/thoat", "/quit", "/exit", "/q"):
            print("Kết thúc phiên.")
            return 0
        if cmd == "/json":
            show_json = not show_json
            print(f"  -> xem JSON đầy đủ: {'BẬT' if show_json else 'TẮT'}")
            continue
        if cmd == "/trace":
            show_trace = not show_trace
            print(f"  -> xem độ trễ: {'BẬT' if show_trace else 'TẮT'}")
            continue
        try:
            resp = pipe.run(query, args.date, trace=show_trace)
        except Exception as exc:                        # không để REPL chết giữa chừng
            LOG.exception("lỗi khi xử lý truy vấn")
            print(f"  !! lỗi: {exc}")
            continue
        payload = resp.to_dict(include_trace=show_trace)
        if show_json:
            print(json.dumps(payload, ensure_ascii=False, indent=2))
        else:
            print(render_human(payload))


def main() -> int:
    load_env_file()
    ap = argparse.ArgumentParser(
        description="Civic AI — phân tích phản ánh, kiến nghị của người dân")
    ap.add_argument("--query", default=None,
                    help="nội dung phản ánh; bỏ trống để vào chế độ hỏi–đáp liên tục")
    ap.add_argument("--date", default=None, help="ngày truy vấn YYYY-MM-DD (mặc định hôm nay)")
    ap.add_argument("--model-dir", default=None)
    ap.add_argument("--device", default="cpu", choices=["cpu", "cuda"])
    ap.add_argument("--backend", default="torch", choices=["torch", "onnx"])
    ap.add_argument("--no-retrieval", action="store_true",
                    help="chỉ chạy NLU + Policy (nhánh cam kết < 100 ms trên CPU)")
    ap.add_argument("--no-verifier", action="store_true")
    ap.add_argument("--no-gate", action="store_true")
    ap.add_argument("--trace", action="store_true", help="in độ trễ từng khối")
    ap.add_argument("--json-only", action="store_true", help="chỉ in JSON, tắt log")
    add_config_args(ap)
    args = ap.parse_args()

    if args.json_only:
        import logging
        logging.disable(logging.INFO)

    cfg = load_config("civic_nlu", args.overrides)
    pipe = CivicPipeline(cfg, device=args.device, backend=args.backend,
                         use_retrieval=not args.no_retrieval,
                         use_verifier=not args.no_verifier,
                         use_gate=not args.no_gate,
                         model_dir=args.model_dir)

    if args.query is None:
        if not sys.stdin.isatty():
            print("Không có --query và stdin không phải terminal.", file=sys.stderr)
            return 2
        return interactive(pipe, args)

    resp = pipe.run(args.query, args.date, trace=args.trace)
    payload: Dict[str, Any] = resp.to_dict(include_trace=args.trace)
    print(json.dumps(payload, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main())