ZhangNguyen commited on
Commit
211968c
·
unverified ·
2 Parent(s): 7f08024026839d

Merge pull request #48 from ZhangNguyen/test2

Browse files
.env.example CHANGED
@@ -1,10 +1,35 @@
1
- OPENAI_API_KEY=your_openai_api_key_here
2
  OPENAI_MODEL=gpt-4o-mini
3
  OPENAI_EMBED_MODEL=text-embedding-3-small
 
4
 
5
- QDRANT_URL=
6
  QDRANT_API_KEY=
7
- QDRANT_COLLECTION=
8
 
9
- # RAG defaults
10
- TOP_K=
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ OPENAI_API_KEY=your_openai_api_key
2
  OPENAI_MODEL=gpt-4o-mini
3
  OPENAI_EMBED_MODEL=text-embedding-3-small
4
+ HF_TOKEN=your_hf_token
5
 
6
+ QDRANT_URL=http://localhost:6333
7
  QDRANT_API_KEY=
8
+ QDRANT_COLLECTION=legal_chunks
9
 
10
+ NORMALIZED_DIR=data/normalized
11
+ NORMALIZED_GLOB=*.*
12
+ GRAPH_SNAPSHOT_PATH=outputs/runtime/runtime_graph_snapshot.json
13
+ BM25_STATS_PATH=outputs/bm25/bm25_stats.json
14
+
15
+ QDRANT_TOP_K=20
16
+ FINAL_TOP_K=5
17
+ CROSS_TOP_K=12
18
+ MAX_GRAPH_HOPS=2
19
+ MAX_GRAPH_NODES=70
20
+
21
+ DOC_TOP_K=3
22
+ CONTENT_TOP_K_PER_DOC=3
23
+ REFERENCE_HYBRID_THRESHOLD=0.85
24
+ RRF_K=60
25
+
26
+ RERANK_MODEL=BAAI/bge-reranker-v2-m3
27
+ RERANK_DEVICE=cpu
28
+ RERANK_TOP_N=12
29
+
30
+ ANSWER_MAX_CONTEXT_PASSAGES=5
31
+ ANSWER_MAX_SOURCE_ITEMS=5
32
+
33
+ APP_HOST=127.0.0.1
34
+ APP_PORT=8000
35
+ CORS_ORIGINS=*
scripts/ingest.py CHANGED
@@ -1,103 +1,13 @@
1
- # import argparse
2
- # from pathlib import Path
3
- #
4
- # from src.rag.openai_clients import get_embedings
5
- # from src.utils.loader import load_document
6
- # from src.rag.chunking_legal import legal_chunk, semantic_merge_safe
7
- # from src.rag.ingestion import upsert_chunks
8
- # from src.utils.normalize_raw import normalize_raw_to_normalized
9
- #
10
- #
11
- # def main():
12
- # parser = argparse.ArgumentParser(description="Ingest legal documents into Qdrant (VN law chunking).")
13
- # parser.add_argument("--input_dir", type=str, default="data/normalized", help="Directory containing .pdf/.txt")
14
- # parser.add_argument("--glob", type=str, default="*.*", help="Glob pattern, e.g. '*.pdf' or '*.*'")
15
- #
16
- # # Document-level metadata for this run
17
- # # parser.add_argument("--law_name", type=str, required=True, help="e.g. NghiDinh07_2026")
18
- # # parser.add_argument("--law_type", type=str, required=True, help="e.g. NghiDinh / ThongTu / Luat / BoLuat")
19
- # # parser.add_argument("--year", type=int, required=True, help="e.g. 2026")
20
- # # parser.add_argument("--source", type=str, default="Local", help="e.g. ChinhPhu / BoNoiVu / Local")
21
- #
22
- # # Chunk settings
23
- # parser.add_argument("--max_chars", type=int, default=1600)
24
- # parser.add_argument("--overlap", type=int, default=120)
25
- #
26
- # # Semantic merge (safe)
27
- # parser.add_argument("--semantic_merge", action="store_true")
28
- # parser.add_argument("--min_chars", type=int, default=350)
29
- # parser.add_argument("--sim_threshold", type=float, default=0.88)
30
- # parser.add_argument("--max_merged_chars", type=int, default=1600)
31
- #
32
- # args = parser.parse_args()
33
- # normalize_raw_to_normalized()
34
- # input_dir = Path(args.input_dir)
35
- # if not input_dir.exists():
36
- # raise RuntimeError(f"Missing folder: {input_dir}")
37
- #
38
- # files = sorted(input_dir.glob(args.glob))
39
- # if not files:
40
- # raise RuntimeError(f"No files matched: {input_dir}/{args.glob}")
41
- #
42
- # # meta = {
43
- # # "law_name": args.law_name,
44
- # # "law_type": args.law_type,
45
- # # "year": args.year,
46
- # # "source": args.source,
47
- # # }
48
- #
49
- # embeddings = get_embedings()
50
- #
51
- # total = 0
52
- # for fp in files:
53
- # if fp.suffix.lower() not in {".pdf", ".txt"}:
54
- # continue
55
- # meta = {
56
- # "law_name": fp.stem, # VanBanGoc_07.2026.ND-CP
57
- # "law_type": "NghiDinh", # tạm hardcode, refine sau
58
- # "year": 2026, # có thể parse sau
59
- # "source": "LocalPDF", # hoặc ChinhPhu / BoNoiVu
60
- # }
61
- # text = load_document(fp)
62
- # print(f"[DEBUG] {fp.name}: text_len={len(text)}")
63
- #
64
- # chunks = legal_chunk(text, max_chars=args.max_chars, overlap=args.overlap)
65
- # print(f"[DEBUG] {fp.name}: chunks={len(chunks)}")
66
- #
67
- # if not chunks:
68
- # print(f"[WARN] {fp.name}: no chunks -> SKIP")
69
- # continue
70
- #
71
- # if args.semantic_merge:
72
- # chunks = semantic_merge_safe(
73
- # chunks,
74
- # embeddings=embeddings,
75
- # min_chars=args.min_chars,
76
- # sim_threshold=args.sim_threshold,
77
- # max_merged_chars=args.max_merged_chars,
78
- # )
79
- #
80
- # n = upsert_chunks(chunks, embeddings=embeddings, meta=meta)
81
- #
82
- # print(f"[OK] {fp.name}: upserted {n} chunks")
83
- # total += n
84
- #
85
- # print("DONE. Total chunks:", total)
86
- #
87
- #
88
- # if __name__ == "__main__":
89
- # main()
90
  from __future__ import annotations
91
 
92
  import argparse
93
- import re
94
  from concurrent.futures import ThreadPoolExecutor, as_completed
95
  from pathlib import Path
96
 
97
  from src.app.settings import settings
98
- from src.rag.openai_clients import get_embedings
99
  from src.rag.chunking_legal import legal_chunk
100
  from src.rag.ingestion import upsert_chunks
 
101
  from src.storage.qdrant_store import ensure_collection, get_qdrant_client
102
  from src.utils.loader import load_document
103
  from src.utils.normalize_raw import normalize_raw_to_normalized
@@ -108,38 +18,16 @@ except Exception:
108
  semantic_merge_safe = None
109
 
110
 
111
- def _slugify(text: str) -> str:
112
- raw = re.sub(r"[^a-zA-Z0-9]+", "_", (text or "").strip().lower())
113
- raw = re.sub(r"_+", "_", raw).strip("_")
114
- return raw or "doc"
115
-
116
-
117
- def _prefix_chunks(chunks: list[dict], doc_prefix: str) -> list[dict]:
118
- out = []
119
- for ch in chunks:
120
- item = dict(ch)
121
- md = dict(item.get("metadata", {}) or {})
122
- if md.get("node_id"):
123
- md["node_id"] = f"{doc_prefix}::{md['node_id']}"
124
- if md.get("chunk_id"):
125
- md["chunk_id"] = f"{doc_prefix}::{md['chunk_id']}"
126
- item["metadata"] = md
127
- out.append(item)
128
- return out
129
-
130
-
131
  def _ingest_single_file(fp: Path, args: argparse.Namespace) -> int:
132
- meta = {
133
- "law_name": fp.stem,
134
- "law_type": "Unknown",
135
- "year": 0,
136
- "source": "LocalFile",
137
- }
138
-
139
  text = load_document(fp)
140
  print(f"[DEBUG] {fp.name}: text_len={len(text)}")
141
 
142
- chunks = legal_chunk(text, max_chars=args.max_chars, overlap=args.overlap)
 
 
 
 
 
143
  print(f"[DEBUG] {fp.name}: chunks={len(chunks)}")
144
 
145
  if not chunks:
@@ -147,6 +35,7 @@ def _ingest_single_file(fp: Path, args: argparse.Namespace) -> int:
147
  return 0
148
 
149
  embeddings = get_embedings()
 
150
  if args.semantic_merge:
151
  if semantic_merge_safe is None:
152
  raise RuntimeError("semantic_merge_safe not available in src.rag.chunking_legal")
@@ -157,11 +46,16 @@ def _ingest_single_file(fp: Path, args: argparse.Namespace) -> int:
157
  sim_threshold=args.sim_threshold,
158
  max_merged_chars=args.max_merged_chars,
159
  )
160
-
161
- doc_prefix = _slugify(fp.stem)
162
- chunks = _prefix_chunks(chunks, doc_prefix)
163
-
164
- n = upsert_chunks(chunks, embeddings=embeddings, meta=meta)
 
 
 
 
 
165
  print(f"[OK] {fp.name}: upserted {n} chunks")
166
  return int(n)
167
 
@@ -201,6 +95,7 @@ def main():
201
  files = sorted(input_dir.glob(args.glob))
202
  if not files:
203
  raise RuntimeError(f"No files matched: {input_dir}/{args.glob}")
 
204
  files = [fp for fp in files if fp.suffix.lower() in {".pdf", ".txt"}]
205
  if not files:
206
  raise RuntimeError(f"No supported files (.pdf/.txt) matched: {input_dir}/{args.glob}")
@@ -210,6 +105,7 @@ def main():
210
 
211
  total = 0
212
  workers = max(1, int(args.upsert_workers))
 
213
  if workers == 1:
214
  for fp in files:
215
  total += _ingest_single_file(fp, args)
@@ -228,4 +124,4 @@ def main():
228
 
229
 
230
  if __name__ == "__main__":
231
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
  import argparse
 
4
  from concurrent.futures import ThreadPoolExecutor, as_completed
5
  from pathlib import Path
6
 
7
  from src.app.settings import settings
 
8
  from src.rag.chunking_legal import legal_chunk
9
  from src.rag.ingestion import upsert_chunks
10
+ from src.rag.openai_clients import get_embedings
11
  from src.storage.qdrant_store import ensure_collection, get_qdrant_client
12
  from src.utils.loader import load_document
13
  from src.utils.normalize_raw import normalize_raw_to_normalized
 
18
  semantic_merge_safe = None
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def _ingest_single_file(fp: Path, args: argparse.Namespace) -> int:
 
 
 
 
 
 
 
22
  text = load_document(fp)
23
  print(f"[DEBUG] {fp.name}: text_len={len(text)}")
24
 
25
+ chunks = legal_chunk(
26
+ text,
27
+ max_chars=args.max_chars,
28
+ overlap=args.overlap,
29
+ fallback_doc_name=fp.stem,
30
+ )
31
  print(f"[DEBUG] {fp.name}: chunks={len(chunks)}")
32
 
33
  if not chunks:
 
35
  return 0
36
 
37
  embeddings = get_embedings()
38
+
39
  if args.semantic_merge:
40
  if semantic_merge_safe is None:
41
  raise RuntimeError("semantic_merge_safe not available in src.rag.chunking_legal")
 
46
  sim_threshold=args.sim_threshold,
47
  max_merged_chars=args.max_merged_chars,
48
  )
49
+ print(f"[DEBUG] {fp.name}: chunks_after_semantic_merge={len(chunks)}")
50
+
51
+ # Không prefix lại node_id/chunk_id ở đây.
52
+ # legal_chunk()/parse_legal_document() đã sinh id theo doc_id chuẩn.
53
+ # Không truyền meta cứng để tránh đè metadata parser.
54
+ n = upsert_chunks(
55
+ chunks,
56
+ embeddings=embeddings,
57
+ meta={},
58
+ )
59
  print(f"[OK] {fp.name}: upserted {n} chunks")
60
  return int(n)
61
 
 
95
  files = sorted(input_dir.glob(args.glob))
96
  if not files:
97
  raise RuntimeError(f"No files matched: {input_dir}/{args.glob}")
98
+
99
  files = [fp for fp in files if fp.suffix.lower() in {".pdf", ".txt"}]
100
  if not files:
101
  raise RuntimeError(f"No supported files (.pdf/.txt) matched: {input_dir}/{args.glob}")
 
105
 
106
  total = 0
107
  workers = max(1, int(args.upsert_workers))
108
+
109
  if workers == 1:
110
  for fp in files:
111
  total += _ingest_single_file(fp, args)
 
124
 
125
 
126
  if __name__ == "__main__":
127
+ main()
src/app/__init__.py ADDED
File without changes
src/app/api/__init__.py ADDED
File without changes
src/app/api/chat.py CHANGED
@@ -29,10 +29,10 @@ class ChatRequestModel(BaseModel):
29
  @router.post("")
30
  def chat(req: ChatRequestModel) -> Dict[str, Any]:
31
  logger.info("Chat request received: chars=%s include_debug=%s", len(req.question or ""), req.include_debug)
 
32
  t0 = time.perf_counter()
33
  graph = ensure_runtime_graph()
34
  t1 = time.perf_counter()
35
- logger.info("Chat step graph_ready: %.2f ms", (t1 - t0) * 1000.0)
36
 
37
  retrieval_result = retrieve_with_graph(
38
  question=req.question,
@@ -45,18 +45,12 @@ def chat(req: ChatRequestModel) -> Dict[str, Any]:
45
  cross_top_k=req.cross_top_k,
46
  )
47
  t2 = time.perf_counter()
48
- logger.info(
49
- "Chat step retrieval_done: %.2f ms passages=%s",
50
- (t2 - t1) * 1000.0,
51
- len(retrieval_result.get("passages", []) or []),
52
- )
53
 
54
  response = answer_with_rag(
55
  question=req.question,
56
  retrieval_result=retrieval_result,
57
  )
58
  t3 = time.perf_counter()
59
- logger.info("Chat step answer_done: %.2f ms total=%.2f ms", (t3 - t2) * 1000.0, (t3 - t0) * 1000.0)
60
 
61
  result: Dict[str, Any] = {
62
  "answer": response.answer,
@@ -70,32 +64,17 @@ def chat(req: ChatRequestModel) -> Dict[str, Any]:
70
  }
71
 
72
  if req.include_debug:
73
- all_passages = retrieval_result.get("passages", []) or []
74
- all_seeds = retrieval_result.get("seed_candidates", []) or []
75
-
76
  result["debug"] = {
77
- "filters": retrieval_result.get("filters", {}),
78
  "mode": retrieval_result.get("mode"),
79
- "query_profile": retrieval_result.get("query_profile", {}),
80
- "qdrant_top_k": retrieval_result.get("qdrant_top_k"),
81
- "final_top_k": retrieval_result.get("final_top_k"),
82
- "cross_top_k": retrieval_result.get("cross_top_k"),
83
-
84
- "seed_candidates_count": len(all_seeds),
85
- "seed_candidate_ids": [
86
- x.get("node_id") for x in all_seeds[:10]
87
- ],
88
- "seed_candidates_preview": [
89
- {
90
- "node_id": x.get("node_id"),
91
- "dense_score": x.get("dense_score"),
92
- "hybrid_score": x.get("hybrid_score"),
93
- "text": str(x.get("text") or "")[:120],
94
- }
95
- for x in all_seeds[:5]
96
- ],
97
-
98
- "passages_count": len(all_passages),
99
- "top_passages": all_passages,
100
  }
101
- return result
 
 
29
  @router.post("")
30
  def chat(req: ChatRequestModel) -> Dict[str, Any]:
31
  logger.info("Chat request received: chars=%s include_debug=%s", len(req.question or ""), req.include_debug)
32
+
33
  t0 = time.perf_counter()
34
  graph = ensure_runtime_graph()
35
  t1 = time.perf_counter()
 
36
 
37
  retrieval_result = retrieve_with_graph(
38
  question=req.question,
 
45
  cross_top_k=req.cross_top_k,
46
  )
47
  t2 = time.perf_counter()
 
 
 
 
 
48
 
49
  response = answer_with_rag(
50
  question=req.question,
51
  retrieval_result=retrieval_result,
52
  )
53
  t3 = time.perf_counter()
 
54
 
55
  result: Dict[str, Any] = {
56
  "answer": response.answer,
 
64
  }
65
 
66
  if req.include_debug:
 
 
 
67
  result["debug"] = {
 
68
  "mode": retrieval_result.get("mode"),
69
+ "reference_threshold": retrieval_result.get("reference_threshold"),
70
+ "max_reference_hybrid": retrieval_result.get("max_reference_hybrid"),
71
+ "rerank_veto": retrieval_result.get("rerank_veto"),
72
+ "veto_reason": retrieval_result.get("veto_reason"),
73
+ "topic_phrases": retrieval_result.get("topic_phrases", []),
74
+ "top_docs": retrieval_result.get("top_docs", []),
75
+ "candidate_pool": retrieval_result.get("candidate_pool", []),
76
+ "passages_count": len(retrieval_result.get("passages", []) or []),
77
+ "insufficient_context": retrieval_result.get("insufficient_context", False),
 
 
 
 
 
 
 
 
 
 
 
 
78
  }
79
+
80
+ return result
src/app/build_bm25.py CHANGED
@@ -22,10 +22,9 @@ def main() -> None:
22
  overlap=args.overlap,
23
  )
24
  save_bm25_stats(stats, args.output)
25
-
26
  print(f"[OK] Saved BM25 stats -> {args.output}")
27
  print(f"N={stats['N']}, avgdl={stats['avgdl']:.2f}, vocab={len(stats['idf'])}")
28
 
29
 
30
  if __name__ == "__main__":
31
- main()
 
22
  overlap=args.overlap,
23
  )
24
  save_bm25_stats(stats, args.output)
 
25
  print(f"[OK] Saved BM25 stats -> {args.output}")
26
  print(f"N={stats['N']}, avgdl={stats['avgdl']:.2f}, vocab={len(stats['idf'])}")
27
 
28
 
29
  if __name__ == "__main__":
30
+ main()
src/app/runtime.py CHANGED
@@ -1,802 +1,220 @@
1
  from __future__ import annotations
2
 
3
- import json
4
  import logging
5
- import re
6
  import time
7
- from collections import defaultdict
8
- from pathlib import Path
9
  from threading import Lock
10
- from typing import Any, Dict, List, Optional
11
 
12
- from src.app.settings import settings
13
- from src.rag.chunking_legal import legal_chunk
14
- from src.rag.document_header import extract_document_header
15
- from src.rag.ingestion import upsert_chunks
16
- from src.rag.openai_clients import get_embedings, get_llm
17
- from src.storage.qdrant_store import ensure_collection, get_qdrant_client
18
- from src.utils.loader import load_document
19
-
20
- try:
21
- from src.rag.chunking_legal import semantic_merge_safe
22
- except Exception:
23
- semantic_merge_safe = None
24
-
25
- try:
26
- from src.rag.rerank_cross import get_cross_encoder
27
- except Exception:
28
- get_cross_encoder = None
29
 
 
30
 
 
31
  _RUNTIME: Dict[str, Any] = {
32
  "graph": None,
33
  "graph_loaded_at": None,
34
  "graph_doc_count": 0,
35
  "last_graph_build_seconds": None,
 
 
36
  "last_reindex_seconds": None,
37
- "graph_build_in_progress": False,
38
- "services_warmed_up": False,
39
- "services_warmup_in_progress": False,
40
- "last_services_warmup_seconds": None,
41
  "startup_preload_completed": False,
42
- "startup_preload_at": None,
43
- "last_startup_preload_seconds": None,
44
- "warmup_last_error": None,
45
  }
46
 
47
- logger = logging.getLogger(__name__)
48
- _RUNTIME_LOCK = Lock()
49
 
50
- SUMMARY_EDGE = "HAS_CHILD_SUMMARY"
51
- SUMMARIZES_EDGE = "SUMMARIZES"
52
-
53
- DOC_NUMBER_IN_TEXT_RE = re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+\b", re.IGNORECASE)
54
-
55
-
56
- def _norm_space(text: str) -> str:
57
- return " ".join((text or "").split()).strip()
58
-
59
-
60
- def _slugify(text: str) -> str:
61
- raw = _norm_space(text).lower()
62
- raw = re.sub(r"[^a-z0-9à-ỹ]+", "_", raw)
63
- raw = re.sub(r"_+", "_", raw).strip("_")
64
- return raw or "doc"
65
-
66
-
67
- def _extract_doc_number(text: str) -> str:
68
- raw = _norm_space(str(text or ""))
69
- if not raw:
70
- return ""
71
- m = DOC_NUMBER_IN_TEXT_RE.search(raw.upper())
72
- return _norm_space(m.group(0)).upper() if m else ""
73
-
74
-
75
- def _infer_year_from_doc_number(text: str) -> int:
76
- m = re.search(r"/(\d{4})/", str(text or ""))
77
- return int(m.group(1)) if m else 0
78
-
79
-
80
- def _normalize_doc_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
81
- md = dict(meta or {})
82
- doc_number = _extract_doc_number(md.get("doc_number") or md.get("title_block") or md.get("lead_block") or "")
83
- if doc_number:
84
- md["doc_number"] = doc_number
85
- year = int(md.get("year") or 0)
86
- if not year and md.get("doc_number"):
87
- md["year"] = _infer_year_from_doc_number(md.get("doc_number"))
88
- if md.get("doc_type") and not md.get("law_type"):
89
- md["law_type"] = md.get("doc_type")
90
- if md.get("law_type") and not md.get("doc_type"):
91
- md["doc_type"] = md.get("law_type")
92
- if md.get("official_title") and not md.get("law_name"):
93
- md["law_name"] = md.get("official_title")
94
- if md.get("law_name") and not md.get("official_title"):
95
- md["official_title"] = md.get("law_name")
96
- return md
97
-
98
-
99
- def _build_adjacency(edges: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
100
- adj: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
101
- for e in edges:
102
- src = e.get("source_id")
103
- if src:
104
- adj[str(src)].append(e)
105
- return dict(adj)
106
-
107
-
108
- def _build_reverse_adjacency(edges: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
109
- rev: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
110
- for e in edges:
111
- tgt = e.get("target_id")
112
- if tgt:
113
- rev[str(tgt)].append(e)
114
- return dict(rev)
115
-
116
-
117
- def _dedup_nodes(nodes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
118
- out: Dict[str, Dict[str, Any]] = {}
119
- for n in nodes:
120
- node_id = n.get("node_id")
121
- if not node_id:
122
- continue
123
- out[str(node_id)] = n
124
- return list(out.values())
125
-
126
-
127
- def _dedup_edges(edges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
128
- seen = set()
129
- out: List[Dict[str, Any]] = []
130
- for e in edges:
131
- sig = (
132
- str(e.get("source_id", "")).strip().lower(),
133
- str(e.get("target_id", "")).strip().lower(),
134
- str(e.get("relation_type", "")).strip().lower(),
135
- )
136
- if sig in seen:
137
- continue
138
- seen.add(sig)
139
- out.append(e)
140
- return out
141
-
142
-
143
- def _snapshot_path() -> Path:
144
- p = Path(settings.graph_snapshot_path)
145
- if not p.is_absolute():
146
- p = Path.cwd() / p
147
- return p
148
-
149
-
150
- def _node_aliases(node: Dict[str, Any]) -> List[str]:
151
- md = dict(node.get("metadata") or {})
152
- aliases: List[str] = []
153
- for raw in [
154
- node.get("node_id"),
155
- md.get("node_id"),
156
- md.get("chunk_id"),
157
- md.get("source_node_id"),
158
- ]:
159
- val = str(raw or "").strip()
160
- if val:
161
- aliases.append(val)
162
- seen = set()
163
- out: List[str] = []
164
- for alias in aliases:
165
- if alias in seen:
166
- continue
167
- seen.add(alias)
168
- out.append(alias)
169
- return out
170
-
171
-
172
- def _build_alias_index(nodes: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
173
- alias_index: Dict[str, Dict[str, Any]] = {}
174
- for node in nodes:
175
- for alias in _node_aliases(node):
176
- alias_index.setdefault(alias, node)
177
- return alias_index
178
-
179
-
180
- def _rebuild_runtime_maps(graph: Dict[str, Any]) -> Dict[str, Any]:
181
- nodes = list(graph.get("nodes", []))
182
- edges = list(graph.get("edges", []))
183
- graph["node_index"] = {str(n["node_id"]): n for n in nodes if n.get("node_id")}
184
- graph["alias_index"] = _build_alias_index(nodes)
185
- graph["adjacency"] = _build_adjacency(edges)
186
- graph["reverse_adjacency"] = _build_reverse_adjacency(edges)
187
- return graph
188
 
189
 
190
- def _save_graph_snapshot(graph: Dict[str, Any]) -> Path:
191
- p = _snapshot_path()
192
- p.parent.mkdir(parents=True, exist_ok=True)
193
- payload = {
194
- "nodes": list(graph.get("nodes", [])),
195
- "edges": list(graph.get("edges", [])),
196
- "doc_index": dict(graph.get("doc_index", {})),
197
- }
198
- p.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
199
- logger.info("Graph snapshot saved: %s", p)
200
- return p
201
-
202
-
203
- def _load_graph_snapshot() -> Optional[Dict[str, Any]]:
204
- p = _snapshot_path()
205
- if not p.exists():
206
- return None
207
- try:
208
- raw = json.loads(p.read_text(encoding="utf-8"))
209
- except Exception as exc:
210
- logger.warning("Cannot read graph snapshot %s: %s", p, exc)
211
- return None
212
-
213
- nodes = list(raw.get("nodes", []))
214
- edges = list(raw.get("edges", []))
215
- if not nodes:
216
- return None
217
-
218
- doc_index = dict(raw.get("doc_index", {}))
219
- parent_to_children: Dict[str, List[str]] = defaultdict(list)
220
- for n in nodes:
221
- md = _normalize_doc_meta(dict(n.get("metadata") or {}))
222
- n["metadata"] = md
223
- parent_id = md.get("parent_id")
224
- if parent_id:
225
- parent_to_children[str(parent_id)].append(str(n.get("node_id")))
226
- doc_id = str(md.get("doc_id") or "")
227
- if doc_id and doc_id not in doc_index:
228
- doc_index[doc_id] = {
229
- "doc_id": doc_id,
230
- "official_title": md.get("official_title") or md.get("law_name") or "",
231
- "doc_type": md.get("doc_type") or md.get("law_type") or "Unknown",
232
- "law_name": md.get("law_name") or md.get("official_title") or "",
233
- "law_type": md.get("law_type") or md.get("doc_type") or "Unknown",
234
- "source": md.get("source") or md.get("issuing_agency") or "LocalFile",
235
- "year": md.get("year") or 0,
236
- "lead_block": md.get("lead_block") or "",
237
- "doc_number": md.get("doc_number"),
238
- "issuing_agency": md.get("issuing_agency"),
239
- }
240
- sibling_map: Dict[str, List[str]] = {}
241
- for _, children in parent_to_children.items():
242
- for child in children:
243
- sibling_map[child] = [x for x in children if x != child]
244
- for n in nodes:
245
- md = _normalize_doc_meta(n.setdefault("metadata", {}))
246
- n["metadata"] = md
247
- node_id = str(n.get("node_id") or "")
248
- md["children_ids"] = parent_to_children.get(node_id, md.get("children_ids", []))
249
- md["sibling_ids"] = sibling_map.get(node_id, md.get("sibling_ids", []))
250
-
251
- graph = {
252
- "nodes": nodes,
253
- "edges": edges,
254
- "doc_index": doc_index,
255
- }
256
- graph = _augment_graph_with_runtime_summaries(graph)
257
- graph = _rebuild_runtime_maps(graph)
258
  return graph
259
 
260
 
261
- def _apply_runtime_graph(graph: Dict[str, Any], built_seconds: float) -> Dict[str, Any]:
262
- _RUNTIME["graph"] = graph
263
- _RUNTIME["graph_loaded_at"] = time.time()
264
- _RUNTIME["graph_doc_count"] = len(graph.get("doc_index", {}))
265
- _RUNTIME["last_graph_build_seconds"] = built_seconds
266
- return graph
 
 
 
 
 
 
 
267
 
268
 
269
  def preload_runtime_graph_from_snapshot() -> bool:
270
- if _RUNTIME["graph"] is not None:
271
- return True
272
- graph = _load_graph_snapshot()
273
- if graph is None:
 
 
274
  return False
275
- _apply_runtime_graph(graph, built_seconds=0.0)
 
 
276
  return True
277
 
278
 
279
- def _prefix_chunks(chunks: List[Dict[str, Any]], doc_prefix: str, *, doc_meta: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
280
- out: List[Dict[str, Any]] = []
281
- for ch in chunks:
282
- item = dict(ch)
283
- md = dict(item.get("metadata", {}) or {})
284
-
285
- for key in ["node_id", "chunk_id", "parent_id"]:
286
- val = md.get(key)
287
- if val:
288
- md[key] = f"{doc_prefix}::{val}"
289
-
290
- for list_key in ["children_ids", "sibling_ids", "source_node_ids"]:
291
- vals = md.get(list_key)
292
- if isinstance(vals, list):
293
- md[list_key] = [f"{doc_prefix}::{x}" for x in vals if x]
294
-
295
- md["doc_id"] = doc_prefix
296
- if doc_meta:
297
- for k, v in doc_meta.items():
298
- if md.get(k) in (None, "") and v not in (None, ""):
299
- md[k] = v
300
-
301
- item["metadata"] = md
302
- out.append(item)
303
- return out
304
-
305
-
306
- def _build_sibling_map(parent_to_children: Dict[str, List[str]]) -> Dict[str, List[str]]:
307
- sibling_map: Dict[str, List[str]] = {}
308
- for _, children in parent_to_children.items():
309
- for child in children:
310
- sibling_map[child] = [x for x in children if x != child]
311
- return sibling_map
312
-
313
-
314
- def _graph_has_summary_nodes(graph: Dict[str, Any], *, doc_id: Optional[str] = None) -> bool:
315
- for node in graph.get("nodes", []) or []:
316
- md = node.get("metadata", {}) or {}
317
- if md.get("artifact_type") != "summary":
318
- continue
319
- if doc_id is None or str(md.get("doc_id") or "") == str(doc_id):
320
- return True
321
- return False
322
-
323
-
324
- def _candidate_doc_summary(doc_id: str, graph: Dict[str, Any], doc_meta: Dict[str, Any]) -> str:
325
- for node in graph.get("nodes", []) or []:
326
- md = node.get("metadata", {}) or {}
327
- if str(md.get("doc_id") or "") != doc_id:
328
- continue
329
- if str(md.get("artifact_type") or "").strip().lower() == "doc_sketch":
330
- text = _norm_space(str(node.get("text") or md.get("doc_summary") or ""))
331
- if text:
332
- return text
333
- text = _norm_space(str(md.get("doc_summary") or ""))
334
- if text:
335
- return text
336
- parts = [
337
- f"Loại văn bản: {str(doc_meta.get('doc_type') or doc_meta.get('law_type') or '').strip()}" if str(doc_meta.get('doc_type') or doc_meta.get('law_type') or '').strip() else '',
338
- f"Tiêu đề: {str(doc_meta.get('official_title') or doc_meta.get('law_name') or '').strip()}" if str(doc_meta.get('official_title') or doc_meta.get('law_name') or '').strip() else '',
339
- f"Số văn bản: {str(doc_meta.get('doc_number') or '').strip()}" if str(doc_meta.get('doc_number') or '').strip() else '',
340
- ]
341
- return _norm_space("\n".join(part for part in parts if part))
342
-
343
-
344
- def _summary_text_from_evidence(node: Dict[str, Any]) -> str:
345
- return _norm_space(
346
- str(node.get("text") or node.get("retrieval_text") or node.get("rerank_text") or "")
347
  )
 
348
 
349
 
350
- def _augment_graph_with_runtime_summaries(graph: Dict[str, Any]) -> Dict[str, Any]:
351
- existing_nodes = list(graph.get("nodes", []))
352
- existing_edges = list(graph.get("edges", []))
353
- doc_index = dict(graph.get("doc_index", {}))
354
-
355
- evidence_by_doc: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
356
- for node in existing_nodes:
357
- md = node.get("metadata", {}) or {}
358
- if md.get("artifact_type") == "summary":
359
- continue
360
- if str(md.get("artifact_type") or "evidence").strip().lower() != "evidence":
361
- continue
362
- doc_id = str(md.get("doc_id") or "").strip()
363
- if doc_id:
364
- evidence_by_doc[doc_id].append(node)
365
-
366
- new_nodes: List[Dict[str, Any]] = []
367
- new_edges: List[Dict[str, Any]] = []
368
-
369
- for doc_id, evidence_nodes in evidence_by_doc.items():
370
- if _graph_has_summary_nodes(graph, doc_id=doc_id):
371
- continue
372
-
373
- doc_meta = dict(doc_index.get(doc_id) or {})
374
- evidence_ids = {str(n.get("node_id")) for n in evidence_nodes if n.get("node_id")}
375
- summary_id_map: Dict[str, str] = {}
376
-
377
- for node in evidence_nodes:
378
- node_id = str(node.get("node_id") or "").strip()
379
- if not node_id:
380
- continue
381
- summary_id_map[node_id] = f"{node_id}::summary"
382
-
383
- root_summary_ids: List[str] = []
384
- for node in evidence_nodes:
385
- node_id = str(node.get("node_id") or "").strip()
386
- if not node_id:
387
- continue
388
- md = dict(node.get("metadata") or {})
389
- summary_id = summary_id_map[node_id]
390
- parent_id = str(md.get("parent_id") or "").strip()
391
- child_ids = [
392
- summary_id_map[str(cid)]
393
- for cid in (md.get("children_ids") or [])
394
- if str(cid) in summary_id_map
395
- ]
396
- if not parent_id or parent_id not in evidence_ids:
397
- root_summary_ids.append(summary_id)
398
-
399
- summary_md = {
400
- **md,
401
- "doc_id": doc_id,
402
- "artifact_type": "summary",
403
- "summary_level": str(node.get("node_type") or md.get("node_type") or "text").strip().lower() or "text",
404
- "source_node_ids": [node_id],
405
- "child_summary_ids": child_ids,
406
- "title": md.get("path_title") or md.get("title") or md.get("article") or md.get("clause") or md.get("point") or md.get("section") or md.get("subsection") or node_id,
407
- "law_name": md.get("law_name") or md.get("official_title") or doc_meta.get("official_title") or doc_meta.get("law_name") or "",
408
- "law_type": md.get("law_type") or md.get("doc_type") or doc_meta.get("doc_type") or doc_meta.get("law_type") or "Unknown",
409
- }
410
- new_nodes.append(
411
- {
412
- "node_id": summary_id,
413
- "node_type": "summary",
414
- "text": _summary_text_from_evidence(node),
415
- "retrieval_text": _summary_text_from_evidence(node),
416
- "rerank_text": _summary_text_from_evidence(node),
417
- "metadata": summary_md,
418
- }
419
- )
420
- new_edges.append(
421
- {
422
- "source_id": summary_id,
423
- "target_id": node_id,
424
- "relation_type": SUMMARIZES_EDGE,
425
- }
426
- )
427
- if parent_id and parent_id in summary_id_map:
428
- new_edges.append(
429
- {
430
- "source_id": summary_id_map[parent_id],
431
- "target_id": summary_id,
432
- "relation_type": SUMMARY_EDGE,
433
- }
434
- )
435
-
436
- doc_summary_text = _candidate_doc_summary(doc_id, graph, doc_meta)
437
- if doc_summary_text:
438
- doc_summary_id = f"{doc_id}::summary::document"
439
- doc_title = _norm_space(
440
- str(doc_meta.get("official_title") or doc_meta.get("law_name") or doc_meta.get("file_name") or doc_id)
441
- )
442
- doc_summary_md = {
443
- **doc_meta,
444
- "doc_id": doc_id,
445
- "artifact_type": "summary",
446
- "summary_level": "document",
447
- "title": doc_title or doc_id,
448
- "document_title": doc_title or doc_id,
449
- "law_name": doc_meta.get("official_title") or doc_meta.get("law_name") or doc_title or doc_id,
450
- "law_type": doc_meta.get("doc_type") or doc_meta.get("law_type") or "Unknown",
451
- "child_summary_ids": sorted(set(root_summary_ids)),
452
- "source_node_ids": [],
453
- }
454
- new_nodes.append(
455
- {
456
- "node_id": doc_summary_id,
457
- "node_type": "summary",
458
- "text": doc_summary_text,
459
- "retrieval_text": doc_summary_text,
460
- "rerank_text": doc_summary_text,
461
- "metadata": doc_summary_md,
462
- }
463
- )
464
- for child_summary_id in sorted(set(root_summary_ids)):
465
- new_edges.append(
466
- {
467
- "source_id": doc_summary_id,
468
- "target_id": child_summary_id,
469
- "relation_type": SUMMARY_EDGE,
470
- }
471
- )
472
- doc_index.setdefault(doc_id, {})["doc_summary_node_id"] = doc_summary_id
473
-
474
- if not new_nodes and not new_edges:
475
- return _rebuild_runtime_maps(graph)
476
-
477
- graph["nodes"] = _dedup_nodes(existing_nodes + new_nodes)
478
- graph["edges"] = _dedup_edges(existing_edges + new_edges)
479
- graph["doc_index"] = doc_index
480
- return _rebuild_runtime_maps(graph)
481
-
482
-
483
- def warmup_runtime_services(force: bool = False) -> Dict[str, Any]:
484
- if _RUNTIME.get("services_warmed_up") and not force:
485
- return {
486
- "services_warmed_up": True,
487
- "seconds": _RUNTIME.get("last_services_warmup_seconds"),
488
- "error": _RUNTIME.get("warmup_last_error"),
489
- }
490
 
491
  with _RUNTIME_LOCK:
492
- if _RUNTIME.get("services_warmed_up") and not force:
493
- return {
494
- "services_warmed_up": True,
495
- "seconds": _RUNTIME.get("last_services_warmup_seconds"),
496
- "error": _RUNTIME.get("warmup_last_error"),
497
- }
498
-
499
- start = time.perf_counter()
500
- _RUNTIME["services_warmup_in_progress"] = True
501
- error_messages: List[str] = []
502
- warmed = {"llm": False, "embeddings": False, "cross_encoder": False}
503
-
504
- try:
505
- get_llm()
506
- warmed["llm"] = True
507
- except Exception as exc:
508
- logger.warning("LLM warmup failed: %s", exc)
509
- error_messages.append(f"llm: {exc}")
510
-
511
- try:
512
- get_embedings()
513
- warmed["embeddings"] = True
514
- except Exception as exc:
515
- logger.warning("Embeddings warmup failed: %s", exc)
516
- error_messages.append(f"embeddings: {exc}")
517
-
518
- if get_cross_encoder is not None:
519
- try:
520
- get_cross_encoder()
521
- warmed["cross_encoder"] = True
522
- except Exception as exc:
523
- logger.warning("Cross-encoder warmup failed: %s", exc)
524
- error_messages.append(f"cross_encoder: {exc}")
525
-
526
- seconds = time.perf_counter() - start
527
- _RUNTIME["last_services_warmup_seconds"] = seconds
528
- _RUNTIME["services_warmed_up"] = any(warmed.values()) and not error_messages
529
- _RUNTIME["warmup_last_error"] = "; ".join(error_messages) if error_messages else None
530
- _RUNTIME["services_warmup_in_progress"] = False
531
- return {
532
- "services_warmed_up": _RUNTIME["services_warmed_up"],
533
- "seconds": seconds,
534
- "details": warmed,
535
- "error": _RUNTIME["warmup_last_error"],
536
- }
537
 
538
 
539
  def preload_runtime_on_startup(
540
  *,
541
  preload_graph_snapshot: bool = True,
542
- build_graph_if_missing: bool = False,
543
  warm_services: bool = True,
544
  ) -> Dict[str, Any]:
545
- start = time.perf_counter()
546
- graph_loaded = False
547
- built_graph = False
548
- warmup_info: Optional[Dict[str, Any]] = None
549
-
550
- if warm_services:
551
- warmup_info = warmup_runtime_services()
552
-
553
- if preload_graph_snapshot:
554
- graph_loaded = preload_runtime_graph_from_snapshot()
555
-
556
- if not graph_loaded and build_graph_if_missing:
557
- build_runtime_graph()
558
- graph_loaded = True
559
- built_graph = True
560
-
561
- seconds = time.perf_counter() - start
562
- _RUNTIME["startup_preload_completed"] = True
563
- _RUNTIME["startup_preload_at"] = time.time()
564
- _RUNTIME["last_startup_preload_seconds"] = seconds
565
- return {
566
- "graph_loaded": graph_loaded,
567
- "graph_built": built_graph,
568
- "warmup": warmup_info,
569
- "seconds": seconds,
570
- }
571
 
 
 
 
 
 
 
572
 
573
- def build_runtime_graph(
574
- input_dir: Optional[str] = None,
575
- glob_pattern: Optional[str] = None,
576
- *,
577
- max_workers: int = 4,
578
- ) -> Dict[str, Any]:
579
- _ = max_workers
580
- start = time.perf_counter()
581
- _RUNTIME["graph_build_in_progress"] = True
582
-
583
- input_dir = input_dir or settings.normalized_dir
584
- glob_pattern = glob_pattern or settings.normalized_glob
585
- logger.info("Graph build started: input_dir=%s glob=%s", input_dir, glob_pattern)
586
-
587
- base = Path(input_dir)
588
- if not base.exists():
589
- raise RuntimeError(f"Missing folder: {base}")
590
-
591
- try:
592
- nodes: List[Dict[str, Any]] = []
593
- edges: List[Dict[str, Any]] = []
594
- doc_index: Dict[str, Dict[str, Any]] = {}
595
- parent_to_children: Dict[str, List[str]] = defaultdict(list)
596
-
597
- for fp in sorted(base.glob(glob_pattern)):
598
- if fp.suffix.lower() not in {".pdf", ".txt"}:
599
- continue
600
-
601
- text = load_document(fp)
602
- header = extract_document_header(text, fallback_name=fp.stem)
603
- doc_prefix = _slugify(fp.stem)
604
- doc_meta = _normalize_doc_meta(header.to_metadata())
605
- doc_meta["doc_id"] = doc_prefix
606
- doc_meta["file_name"] = fp.name
607
- doc_meta["source_path"] = str(fp)
608
- doc_index[doc_prefix] = doc_meta
609
-
610
- chunks = legal_chunk(text, fallback_doc_name=fp.stem)
611
- chunks = _prefix_chunks(chunks, doc_prefix, doc_meta=doc_meta)
612
-
613
- for ch in chunks:
614
- md = _normalize_doc_meta(dict(ch.get("metadata") or {}))
615
- node_id = str(md.get("node_id") or md.get("chunk_id") or "")
616
- if not node_id:
617
- continue
618
- node = {
619
- "node_id": node_id,
620
- "node_type": md.get("node_type") or "text",
621
- "text": str(ch.get("text") or "").strip(),
622
- "retrieval_text": str(ch.get("retrieval_text") or ch.get("text") or "").strip(),
623
- "rerank_text": str(ch.get("rerank_text") or ch.get("retrieval_text") or ch.get("text") or "").strip(),
624
- "metadata": md,
625
- }
626
- nodes.append(node)
627
- parent_id = md.get("parent_id")
628
- if parent_id:
629
- edges.append({"source_id": str(parent_id), "target_id": node_id, "relation_type": "HAS_CHILD"})
630
- parent_to_children[str(parent_id)].append(node_id)
631
-
632
- nodes = _dedup_nodes(nodes)
633
- edges = _dedup_edges(edges)
634
- sibling_map = _build_sibling_map(parent_to_children)
635
- node_index = {str(n["node_id"]): n for n in nodes if n.get("node_id")}
636
- for node_id, node in node_index.items():
637
- md = node.setdefault("metadata", {})
638
- md["children_ids"] = parent_to_children.get(node_id, md.get("children_ids", []))
639
- md["sibling_ids"] = sibling_map.get(node_id, md.get("sibling_ids", []))
640
- doc_id = str(md.get("doc_id") or "")
641
- if doc_id in doc_index:
642
- for key, val in doc_index[doc_id].items():
643
- if md.get(key) in (None, "") and val not in (None, ""):
644
- md[key] = val
645
- graph = {
646
- "nodes": nodes,
647
- "edges": edges,
648
- "doc_index": doc_index,
649
- }
650
- graph = _augment_graph_with_runtime_summaries(graph)
651
- graph = _rebuild_runtime_maps(graph)
652
- _apply_runtime_graph(graph, built_seconds=time.perf_counter() - start)
653
- _save_graph_snapshot(graph)
654
- logger.info(
655
- "Graph build finished: docs=%s nodes=%s edges=%s aliases=%s took=%.2fs",
656
- len(doc_index), len(graph.get("nodes", [])), len(graph.get("edges", [])), len(graph.get("alias_index", {})), _RUNTIME["last_graph_build_seconds"]
657
- )
658
- return graph
659
- finally:
660
- _RUNTIME["graph_build_in_progress"] = False
661
 
 
 
662
 
663
- def ensure_runtime_graph() -> Dict[str, Any]:
664
- if _RUNTIME["graph"] is not None:
665
- return _RUNTIME["graph"]
666
- if preload_runtime_graph_from_snapshot():
667
- return _RUNTIME["graph"]
668
- return build_runtime_graph()
669
 
 
 
 
 
670
 
671
- def get_runtime_status() -> Dict[str, Any]:
672
- graph = _RUNTIME["graph"]
673
- summary_count = 0
674
- if graph is not None:
675
- for node in graph.get("nodes", []) or []:
676
- md = node.get("metadata", {}) or {}
677
- if md.get("artifact_type") == "summary":
678
- summary_count += 1
 
 
 
 
 
 
 
 
679
  return {
680
- "graph_loaded": graph is not None,
681
- "graph_loaded_at": _RUNTIME["graph_loaded_at"],
 
682
  "graph_doc_count": _RUNTIME["graph_doc_count"],
683
- "graph_node_count": len((graph or {}).get("nodes", [])),
684
- "graph_edge_count": len((graph or {}).get("edges", [])),
685
- "graph_alias_count": len((graph or {}).get("alias_index", {})),
686
- "graph_summary_count": summary_count,
687
- "last_graph_build_seconds": _RUNTIME["last_graph_build_seconds"],
688
- "last_reindex_seconds": _RUNTIME["last_reindex_seconds"],
689
- "graph_build_in_progress": _RUNTIME["graph_build_in_progress"],
690
- "graph_snapshot_path": str(_snapshot_path()),
691
- "graph_snapshot_exists": _snapshot_path().exists(),
692
- "services_warmed_up": _RUNTIME["services_warmed_up"],
693
- "services_warmup_in_progress": _RUNTIME["services_warmup_in_progress"],
694
- "last_services_warmup_seconds": _RUNTIME["last_services_warmup_seconds"],
695
- "startup_preload_completed": _RUNTIME["startup_preload_completed"],
696
- "startup_preload_at": _RUNTIME["startup_preload_at"],
697
- "last_startup_preload_seconds": _RUNTIME["last_startup_preload_seconds"],
698
- "warmup_last_error": _RUNTIME["warmup_last_error"],
699
  }
700
 
701
 
702
- def save_current_runtime_graph_snapshot(force_build: bool = False) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
703
  graph = _RUNTIME.get("graph")
704
- if graph is None:
705
- if not force_build:
706
- raise RuntimeError("Runtime graph is empty. Build/load graph first or use force_build=true.")
707
- graph = build_runtime_graph()
708
- _save_graph_snapshot(graph)
709
- return {
710
- "snapshot_path": str(_snapshot_path()),
711
- "snapshot_exists": _snapshot_path().exists(),
712
- "graph_nodes": len(graph.get("nodes", [])),
713
- "graph_edges": len(graph.get("edges", [])),
714
- "graph_aliases": len(graph.get("alias_index", {})),
715
- "graph_summaries": sum(1 for n in graph.get("nodes", []) if (n.get("metadata", {}) or {}).get("artifact_type") == "summary"),
716
- }
717
 
 
 
 
 
718
 
719
- def reindex_qdrant_from_normalized(
720
- input_dir: Optional[str] = None,
721
- glob_pattern: Optional[str] = None,
722
- *,
723
- semantic_merge: bool = False,
724
- min_chars: int = 350,
725
- sim_threshold: float = 0.88,
726
- max_merged_chars: int = 1600,
727
- max_chars: int = 1600,
728
- overlap: int = 120,
729
- ) -> Dict[str, Any]:
730
- start = time.perf_counter()
731
-
732
- input_dir = input_dir or settings.normalized_dir
733
- glob_pattern = glob_pattern or settings.normalized_glob
734
-
735
- base = Path(input_dir)
736
- if not base.exists():
737
- raise RuntimeError(f"Missing folder: {base}")
738
-
739
- embeddings = get_embedings()
740
- client = get_qdrant_client()
741
- ensure_collection(client)
742
-
743
- total_chunks = 0
744
- total_docs = 0
745
-
746
- for fp in sorted(base.glob(glob_pattern)):
747
- if fp.suffix.lower() not in {".pdf", ".txt"}:
748
- continue
749
-
750
- text = load_document(fp)
751
- header = extract_document_header(text, fallback_name=fp.stem)
752
- doc_title = fp.stem
753
- doc_prefix = _slugify(doc_title)
754
- doc_meta = _normalize_doc_meta(header.to_metadata())
755
- doc_meta["doc_id"] = doc_prefix
756
-
757
- chunks = legal_chunk(text, max_chars=max_chars, overlap=overlap, fallback_doc_name=fp.stem)
758
- if not chunks:
759
- continue
760
-
761
- if semantic_merge:
762
- if semantic_merge_safe is None:
763
- raise RuntimeError("semantic_merge_safe not available in src.rag.chunking_legal")
764
- chunks = semantic_merge_safe(
765
- chunks,
766
- embeddings=embeddings,
767
- min_chars=min_chars,
768
- sim_threshold=sim_threshold,
769
- max_merged_chars=max_merged_chars,
770
- )
771
-
772
- chunks = _prefix_chunks(chunks, doc_prefix, doc_meta=doc_meta)
773
- n = upsert_chunks(chunks, embeddings=embeddings, meta=doc_meta)
774
- total_chunks += int(n)
775
- total_docs += 1
776
-
777
- _RUNTIME["last_reindex_seconds"] = time.perf_counter() - start
778
  return {
779
- "docs_indexed": total_docs,
780
- "chunks_indexed": total_chunks,
781
- "seconds": _RUNTIME["last_reindex_seconds"],
782
  }
783
 
784
 
785
- def rebuild_everything(
786
- input_dir: Optional[str] = None,
787
- glob_pattern: Optional[str] = None,
788
- ) -> Dict[str, Any]:
789
- qdrant_info = reindex_qdrant_from_normalized(
790
- input_dir=input_dir,
791
- glob_pattern=glob_pattern,
792
- )
793
- graph = build_runtime_graph(
794
- input_dir=input_dir,
795
- glob_pattern=glob_pattern,
796
- )
797
  return {
798
- "qdrant": qdrant_info,
799
- "graph_nodes": len(graph.get("nodes", [])),
800
- "graph_edges": len(graph.get("edges", [])),
801
- "status": get_runtime_status(),
802
- }
 
 
 
 
 
1
  from __future__ import annotations
2
 
 
3
  import logging
 
4
  import time
 
 
5
  from threading import Lock
6
+ from typing import Any, Dict, Optional
7
 
8
+ from src.rag.graph_builder import (
9
+ build_runtime_graph as _build_runtime_graph,
10
+ load_graph_snapshot,
11
+ rebuild_everything as _rebuild_everything,
12
+ reindex_qdrant_from_normalized as _reindex_qdrant_from_normalized,
13
+ save_graph_snapshot,
14
+ )
 
 
 
 
 
 
 
 
 
 
15
 
16
+ logger = logging.getLogger(__name__)
17
 
18
+ _RUNTIME_LOCK = Lock()
19
  _RUNTIME: Dict[str, Any] = {
20
  "graph": None,
21
  "graph_loaded_at": None,
22
  "graph_doc_count": 0,
23
  "last_graph_build_seconds": None,
24
+ "last_snapshot_load_seconds": None,
25
+ "last_snapshot_save_seconds": None,
26
  "last_reindex_seconds": None,
 
 
 
 
27
  "startup_preload_completed": False,
 
 
 
28
  }
29
 
 
 
30
 
31
+ def _graph_doc_count(graph: Optional[Dict[str, Any]]) -> int:
32
+ if not graph:
33
+ return 0
34
+ doc_index = graph.get("doc_index", {}) or {}
35
+ return len(doc_index)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
+ def _apply_runtime_graph(graph: Optional[Dict[str, Any]], *, load_seconds: float = 0.0, build_seconds: Optional[float] = None) -> Optional[Dict[str, Any]]:
39
+ _RUNTIME["graph"] = graph
40
+ _RUNTIME["graph_loaded_at"] = time.time() if graph else None
41
+ _RUNTIME["graph_doc_count"] = _graph_doc_count(graph)
42
+ _RUNTIME["last_snapshot_load_seconds"] = load_seconds
43
+ if build_seconds is not None:
44
+ _RUNTIME["last_graph_build_seconds"] = build_seconds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  return graph
46
 
47
 
48
+ def clear_runtime_graph() -> Dict[str, Any]:
49
+ with _RUNTIME_LOCK:
50
+ _RUNTIME["graph"] = None
51
+ _RUNTIME["graph_loaded_at"] = None
52
+ _RUNTIME["graph_doc_count"] = 0
53
+ _RUNTIME["last_graph_build_seconds"] = None
54
+ _RUNTIME["last_snapshot_load_seconds"] = None
55
+ _RUNTIME["last_snapshot_save_seconds"] = None
56
+ _RUNTIME["startup_preload_completed"] = False
57
+ return {
58
+ "cleared": True,
59
+ "graph_loaded": False,
60
+ }
61
 
62
 
63
  def preload_runtime_graph_from_snapshot() -> bool:
64
+ t0 = time.perf_counter()
65
+ graph = load_graph_snapshot()
66
+ elapsed = time.perf_counter() - t0
67
+
68
+ if not graph:
69
+ logger.info("No snapshot loaded.")
70
  return False
71
+
72
+ _apply_runtime_graph(graph, load_seconds=elapsed)
73
+ logger.info("Runtime graph loaded from snapshot in %.2fs with %s docs.", elapsed, _RUNTIME["graph_doc_count"])
74
  return True
75
 
76
 
77
+ def build_runtime_graph() -> Dict[str, Any]:
78
+ t0 = time.perf_counter()
79
+ built_graph = _build_runtime_graph()
80
+ build_elapsed = time.perf_counter() - t0
81
+
82
+ save_t0 = time.perf_counter()
83
+ save_graph_snapshot(built_graph)
84
+ save_elapsed = time.perf_counter() - save_t0
85
+ _RUNTIME["last_snapshot_save_seconds"] = save_elapsed
86
+
87
+ load_t0 = time.perf_counter()
88
+ loaded_graph = load_graph_snapshot()
89
+ load_elapsed = time.perf_counter() - load_t0
90
+
91
+ if not loaded_graph:
92
+ # fallback rất hiếm: save xong mà load lại lỗi thì vẫn giữ graph vừa build
93
+ logger.warning("Snapshot save succeeded but reload failed. Falling back to in-memory built graph.")
94
+ _apply_runtime_graph(built_graph, load_seconds=0.0, build_seconds=build_elapsed)
95
+ return built_graph
96
+
97
+ _apply_runtime_graph(loaded_graph, load_seconds=load_elapsed, build_seconds=build_elapsed)
98
+ logger.info(
99
+ "Runtime graph built in %.2fs, snapshot saved in %.2fs, reloaded from snapshot in %.2fs, docs=%s.",
100
+ build_elapsed,
101
+ save_elapsed,
102
+ load_elapsed,
103
+ _RUNTIME["graph_doc_count"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  )
105
+ return loaded_graph
106
 
107
 
108
+ def ensure_runtime_graph() -> Dict[str, Any]:
109
+ graph = _RUNTIME.get("graph")
110
+ if graph is not None:
111
+ return graph
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  with _RUNTIME_LOCK:
114
+ graph = _RUNTIME.get("graph")
115
+ if graph is not None:
116
+ return graph
117
+
118
+ if preload_runtime_graph_from_snapshot():
119
+ return _RUNTIME["graph"]
120
+
121
+ return build_runtime_graph()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
 
124
  def preload_runtime_on_startup(
125
  *,
126
  preload_graph_snapshot: bool = True,
127
+ build_graph_if_missing: bool = True,
128
  warm_services: bool = True,
129
  ) -> Dict[str, Any]:
130
+ del warm_services
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
+ with _RUNTIME_LOCK:
133
+ if preload_graph_snapshot:
134
+ loaded = preload_runtime_graph_from_snapshot()
135
+ if loaded:
136
+ _RUNTIME["startup_preload_completed"] = True
137
+ return get_runtime_status()
138
 
139
+ if build_graph_if_missing:
140
+ build_runtime_graph()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
+ _RUNTIME["startup_preload_completed"] = True
143
+ return get_runtime_status()
144
 
 
 
 
 
 
 
145
 
146
+ def rebuild_everything() -> Dict[str, Any]:
147
+ t0 = time.perf_counter()
148
+ result = _rebuild_everything()
149
+ elapsed = time.perf_counter() - t0
150
 
151
+ graph = result.get("graph")
152
+ if graph:
153
+ save_t0 = time.perf_counter()
154
+ save_graph_snapshot(graph)
155
+ _RUNTIME["last_snapshot_save_seconds"] = time.perf_counter() - save_t0
156
+
157
+ load_t0 = time.perf_counter()
158
+ reloaded = load_graph_snapshot()
159
+ load_elapsed = time.perf_counter() - load_t0
160
+
161
+ if reloaded:
162
+ _apply_runtime_graph(reloaded, load_seconds=load_elapsed)
163
+ else:
164
+ _apply_runtime_graph(graph, load_seconds=0.0)
165
+
166
+ _RUNTIME["last_reindex_seconds"] = elapsed
167
  return {
168
+ "ok": True,
169
+ "seconds": elapsed,
170
+ "graph_loaded": _RUNTIME["graph"] is not None,
171
  "graph_doc_count": _RUNTIME["graph_doc_count"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  }
173
 
174
 
175
+ def reindex_qdrant_from_normalized() -> Dict[str, Any]:
176
+ t0 = time.perf_counter()
177
+ result = _reindex_qdrant_from_normalized()
178
+ elapsed = time.perf_counter() - t0
179
+ _RUNTIME["last_reindex_seconds"] = elapsed
180
+
181
+ payload = dict(result or {})
182
+ payload["seconds"] = elapsed
183
+ return payload
184
+
185
+
186
+ def save_current_runtime_graph_snapshot() -> Dict[str, Any]:
187
  graph = _RUNTIME.get("graph")
188
+ if not graph:
189
+ return {
190
+ "ok": False,
191
+ "reason": "graph_not_loaded",
192
+ }
 
 
 
 
 
 
 
 
193
 
194
+ t0 = time.perf_counter()
195
+ save_graph_snapshot(graph)
196
+ elapsed = time.perf_counter() - t0
197
+ _RUNTIME["last_snapshot_save_seconds"] = elapsed
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  return {
200
+ "ok": True,
201
+ "seconds": elapsed,
202
+ "graph_doc_count": _RUNTIME["graph_doc_count"],
203
  }
204
 
205
 
206
+ def get_runtime_graph() -> Optional[Dict[str, Any]]:
207
+ return _RUNTIME.get("graph")
208
+
209
+
210
+ def get_runtime_status() -> Dict[str, Any]:
 
 
 
 
 
 
 
211
  return {
212
+ "graph_loaded": _RUNTIME.get("graph") is not None,
213
+ "graph_loaded_at": _RUNTIME.get("graph_loaded_at"),
214
+ "graph_doc_count": _RUNTIME.get("graph_doc_count", 0),
215
+ "last_graph_build_seconds": _RUNTIME.get("last_graph_build_seconds"),
216
+ "last_snapshot_load_seconds": _RUNTIME.get("last_snapshot_load_seconds"),
217
+ "last_snapshot_save_seconds": _RUNTIME.get("last_snapshot_save_seconds"),
218
+ "last_reindex_seconds": _RUNTIME.get("last_reindex_seconds"),
219
+ "startup_preload_completed": _RUNTIME.get("startup_preload_completed", False),
220
+ }
src/app/settings.py CHANGED
@@ -1,14 +1,28 @@
1
  from __future__ import annotations
2
 
3
  import os
 
4
  from typing import List
5
 
6
  from dotenv import load_dotenv
7
- from pydantic import BaseModel
8
 
9
  load_dotenv()
10
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def _split_csv(raw: str) -> List[str]:
13
  raw = (raw or "").strip()
14
  if not raw:
@@ -16,10 +30,12 @@ def _split_csv(raw: str) -> List[str]:
16
  return [x.strip() for x in raw.split(",") if x.strip()]
17
 
18
 
19
- class Settings(BaseModel):
 
20
  openai_api_key: str = os.getenv("OPENAI_API_KEY", "")
21
  openai_model: str = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
22
  openai_embed_model: str = os.getenv("OPENAI_EMBED_MODEL", "text-embedding-3-small")
 
23
 
24
  qdrant_url: str = os.getenv("QDRANT_URL", "http://localhost:6333")
25
  qdrant_api_key: str = os.getenv("QDRANT_API_KEY", "")
@@ -28,33 +44,32 @@ class Settings(BaseModel):
28
  normalized_dir: str = os.getenv("NORMALIZED_DIR", "data/normalized")
29
  normalized_glob: str = os.getenv("NORMALIZED_GLOB", "*.*")
30
  graph_snapshot_path: str = os.getenv("GRAPH_SNAPSHOT_PATH", "outputs/runtime/runtime_graph_snapshot.json")
31
-
32
- qdrant_top_k: int = int(os.getenv("QDRANT_TOP_K", "40"))
33
- bm25_top_k: int = int(os.getenv("BM25_TOP_K", "12"))
34
- final_top_k: int = int(os.getenv("FINAL_TOP_K", "8"))
35
- cross_top_k: int = int(os.getenv("CROSS_TOP_K", "8"))
36
- hybrid_alpha: float = float(os.getenv("HYBRID_ALPHA", "0.58"))
37
-
38
- bundle_max_children: int = int(os.getenv("BUNDLE_MAX_CHILDREN", "3"))
39
- bundle_max_siblings: int = int(os.getenv("BUNDLE_MAX_SIBLINGS", "2"))
40
-
41
  bm25_stats_path: str = os.getenv("BM25_STATS_PATH", "outputs/bm25/bm25_stats.json")
42
 
43
- answer_max_context_passages: int = int(os.getenv("ANSWER_MAX_CONTEXT_PASSAGES", "6"))
44
- answer_max_source_items: int = int(os.getenv("ANSWER_MAX_SOURCE_ITEMS", "6"))
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  rerank_model: str = os.getenv("RERANK_MODEL", "BAAI/bge-reranker-v2-m3")
47
  rerank_device: str = os.getenv("RERANK_DEVICE", "cpu")
48
- rerank_top_n: int = int(os.getenv("RERANK_TOP_N", "12"))
49
 
50
  app_host: str = os.getenv("APP_HOST", "127.0.0.1")
51
- app_port: int = int(os.getenv("APP_PORT", "8000"))
52
- cors_origins: List[str] = _split_csv(os.getenv("CORS_ORIGINS", "*"))
53
 
54
- poppler_path: str = os.getenv("POPPLER_PATH", "")
55
- tesseract_cmd: str = os.getenv("TESSERACT_CMD", "")
56
- tesseract_lang: str = os.getenv("TESSERACT_LANG", "vie")
57
- ocr_dpi: int = int(os.getenv("OCR_DPI", "300"))
58
 
59
 
60
  settings = Settings()
 
1
  from __future__ import annotations
2
 
3
  import os
4
+ from dataclasses import dataclass
5
  from typing import List
6
 
7
  from dotenv import load_dotenv
 
8
 
9
  load_dotenv()
10
 
11
 
12
+ def _get_int(name: str, default: int) -> int:
13
+ try:
14
+ return int(os.getenv(name, str(default)))
15
+ except Exception:
16
+ return default
17
+
18
+
19
+ def _get_float(name: str, default: float) -> float:
20
+ try:
21
+ return float(os.getenv(name, str(default)))
22
+ except Exception:
23
+ return default
24
+
25
+
26
  def _split_csv(raw: str) -> List[str]:
27
  raw = (raw or "").strip()
28
  if not raw:
 
30
  return [x.strip() for x in raw.split(",") if x.strip()]
31
 
32
 
33
+ @dataclass(frozen=True)
34
+ class Settings:
35
  openai_api_key: str = os.getenv("OPENAI_API_KEY", "")
36
  openai_model: str = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
37
  openai_embed_model: str = os.getenv("OPENAI_EMBED_MODEL", "text-embedding-3-small")
38
+ hf_token: str = os.getenv("HF_TOKEN", "")
39
 
40
  qdrant_url: str = os.getenv("QDRANT_URL", "http://localhost:6333")
41
  qdrant_api_key: str = os.getenv("QDRANT_API_KEY", "")
 
44
  normalized_dir: str = os.getenv("NORMALIZED_DIR", "data/normalized")
45
  normalized_glob: str = os.getenv("NORMALIZED_GLOB", "*.*")
46
  graph_snapshot_path: str = os.getenv("GRAPH_SNAPSHOT_PATH", "outputs/runtime/runtime_graph_snapshot.json")
 
 
 
 
 
 
 
 
 
 
47
  bm25_stats_path: str = os.getenv("BM25_STATS_PATH", "outputs/bm25/bm25_stats.json")
48
 
49
+ doc_top_k: int = _get_int("DOC_TOP_K", 3)
50
+ content_top_k_per_doc: int = _get_int("CONTENT_TOP_K_PER_DOC", 3)
51
+ final_top_k: int = _get_int("FINAL_TOP_K", 5)
52
+ cross_top_k: int = _get_int("CROSS_TOP_K", 8)
53
+ reference_hybrid_threshold: float = _get_float("REFERENCE_HYBRID_THRESHOLD", 0.85)
54
+ doc_sketch_hybrid_threshold: float = _get_float("DOC_SKETCH_HYBRID_THRESHOLD", 0.82)
55
+ cross_rerank_min_score: float = _get_float("CROSS_RERANK_MIN_SCORE", 0.05)
56
+ hybrid_alpha: float = _get_float("HYBRID_ALPHA", 0.55)
57
+ rrf_k: int = _get_int("RRF_K", 60)
58
+ th2_passage_top_k: int = _get_int("TH2_PASSAGE_TOP_K", 12)
59
+
60
+ answer_max_context_passages: int = _get_int("ANSWER_MAX_CONTEXT_PASSAGES", 5)
61
+ answer_max_source_items: int = _get_int("ANSWER_MAX_SOURCE_ITEMS", 5)
62
 
63
  rerank_model: str = os.getenv("RERANK_MODEL", "BAAI/bge-reranker-v2-m3")
64
  rerank_device: str = os.getenv("RERANK_DEVICE", "cpu")
65
+ rerank_top_n: int = _get_int("RERANK_TOP_N", 12)
66
 
67
  app_host: str = os.getenv("APP_HOST", "127.0.0.1")
68
+ app_port: int = _get_int("APP_PORT", 8000)
69
+ cors_origins: List[str] = None # type: ignore[assignment]
70
 
71
+ def __post_init__(self) -> None:
72
+ object.__setattr__(self, "cors_origins", _split_csv(os.getenv("CORS_ORIGINS", "*")))
 
 
73
 
74
 
75
  settings = Settings()
src/rag/__init__.py ADDED
File without changes
src/rag/chunking_legal.py CHANGED
@@ -188,30 +188,65 @@ def parse_legal_document(text: str, *, fallback_doc_name: str = "") -> ParsedLeg
188
  current_item = None
189
  current_anchor = node
190
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  point_m = POINT_RE.match(line)
193
- if point_m and current_clause is not None:
194
  ch = point_m.group(1).lower()
195
  point = f"Điểm {ch}"
 
 
 
 
 
 
 
 
 
 
 
196
  node = LegalNode(
197
- node_id=_new_node_id(header.doc_id, "point", current_article.article or "", current_clause.clause or "", ch),
198
  doc_id=header.doc_id,
199
  node_type="point",
200
  label=point,
201
  text=line,
202
- parent_id=current_clause.node_id,
203
  order_index=order,
204
- level=3,
205
  article=current_article.article if current_article else None,
206
  clause=current_clause.clause if current_clause else None,
207
  point=point,
 
208
  )
209
  order += 1
210
  nodes.append(node)
211
  node_index[node.node_id] = node
212
- current_clause.children_ids.append(node.node_id)
213
  current_point = node
214
- current_item = None
215
  current_anchor = node
216
  continue
217
 
 
188
  current_item = None
189
  current_anchor = node
190
  continue
191
+ if clause_m and current_article is None:
192
+ item_num = clause_m.group(1)
193
+ label = clause_m.group(0)
194
+ parent = current_section or doc_node
195
+ node = LegalNode(
196
+ node_id=_new_node_id(header.doc_id, "item", parent.label, item_num),
197
+ doc_id=header.doc_id,
198
+ node_type="item",
199
+ label=label,
200
+ text=line,
201
+ parent_id=parent.node_id,
202
+ order_index=order,
203
+ level=parent.level + 1,
204
+ item=item_num,
205
+ )
206
+ order += 1
207
+ nodes.append(node)
208
+ node_index[node.node_id] = node
209
+ parent.children_ids.append(node.node_id)
210
+ current_item = node
211
+ current_clause = None
212
+ current_point = None
213
+ current_anchor = node
214
+ continue
215
 
216
  point_m = POINT_RE.match(line)
217
+ if point_m and (current_clause is not None or current_item is not None):
218
  ch = point_m.group(1).lower()
219
  point = f"Điểm {ch}"
220
+ parent = current_clause or current_item
221
+
222
+ point_parent_1 = (
223
+ current_article.article if current_article else
224
+ (current_item.item if current_item else "")
225
+ )
226
+ point_parent_2 = (
227
+ current_clause.clause if current_clause else
228
+ (current_item.label if current_item else "")
229
+ )
230
+
231
  node = LegalNode(
232
+ node_id=_new_node_id(header.doc_id, "point", point_parent_1, point_parent_2, ch),
233
  doc_id=header.doc_id,
234
  node_type="point",
235
  label=point,
236
  text=line,
237
+ parent_id=parent.node_id,
238
  order_index=order,
239
+ level=parent.level + 1,
240
  article=current_article.article if current_article else None,
241
  clause=current_clause.clause if current_clause else None,
242
  point=point,
243
+ item=current_item.item if current_item else None,
244
  )
245
  order += 1
246
  nodes.append(node)
247
  node_index[node.node_id] = node
248
+ parent.children_ids.append(node.node_id)
249
  current_point = node
 
250
  current_anchor = node
251
  continue
252
 
src/rag/document_header.py CHANGED
@@ -2,7 +2,7 @@ from __future__ import annotations
2
 
3
  import re
4
  from dataclasses import dataclass, asdict
5
- from typing import Dict, List, Optional
6
 
7
  DOC_TYPES = [
8
  "BỘ LUẬT",
@@ -20,129 +20,309 @@ DOC_TYPES = [
20
  "ĐỀ ÁN",
21
  ]
22
 
23
- STOP_TITLE_PATTERNS = [
 
 
 
24
  re.compile(r"^Điều\s+\d+", re.IGNORECASE),
25
- re.compile(r"^(Bộ trưởng|Thủ tướng|Chính phủ|Ủy ban nhân dân|Chủ tịch|Theo|Tình hình|Căn cứ|Xét)\b", re.IGNORECASE),
 
 
26
  re.compile(r"^\d+\.\s+"),
27
  re.compile(r"^[a-zđ]\)\s+", re.IGNORECASE),
28
  ]
29
 
30
- AGENCY_SKIP = (
31
  "CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM",
32
  "Độc lập - Tự do - Hạnh phúc",
33
- )
34
-
35
- NUMBER_RE = re.compile(r"^Số\s*:?\s*(.+)$", re.IGNORECASE)
36
- DOC_NUMBER_IN_TEXT_RE = re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+\b", re.IGNORECASE)
 
 
 
 
 
37
  DATE_RE = re.compile(
38
- r"(?:^|,\s*)(?P<place>[A-ZÀ-Ỵa-zà-ỵ\s\.\-]+),\s*ngày\s*(?P<day>\d{1,2})\s*tháng\s*(?P<month>\d{1,2})\s*năm\s*(?P<year>\d{4})",
39
  re.IGNORECASE,
40
  )
 
41
  ARTICLE_START_RE = re.compile(r"^Điều\s+\d+", re.IGNORECASE)
 
42
  ITEM_START_RE = re.compile(r"^\d+\.\s+")
43
  POINT_START_RE = re.compile(r"^[a-zđ]\)\s+", re.IGNORECASE)
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  def _norm_space(text: str) -> str:
47
- return " ".join((text or "").split()).strip()
48
 
49
 
50
  def _slugify(text: str) -> str:
51
  raw = _norm_space(text).lower()
52
  raw = re.sub(r"[^a-z0-9à-ỹ]+", "_", raw)
53
  raw = re.sub(r"_+", "_", raw).strip("_")
54
- return raw or "doc"
55
 
56
 
57
  def _clean_lines(text: str) -> List[str]:
58
  out: List[str] = []
59
  for raw in str(text or "").splitlines():
60
- line = raw.replace("\ufeff", " ").strip()
61
- line = re.sub(r"\s+", " ", line).strip()
62
  if line:
63
  out.append(line)
64
  return out
65
 
66
 
67
- def _clean_doc_number(text: str) -> Optional[str]:
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  raw = _norm_space(str(text or ""))
69
  if not raw:
70
- return None
71
- m = DOC_NUMBER_IN_TEXT_RE.search(raw.upper())
72
  if not m:
73
- return None
74
- return _norm_space(m.group(0)).upper()
 
 
 
75
 
76
 
77
- def _is_upper_like(line: str) -> bool:
78
- letters = [ch for ch in line if ch.isalpha()]
79
- if len(letters) < 4:
80
- return False
81
- upper = sum(1 for ch in letters if ch.isupper())
82
- return upper / max(len(letters), 1) >= 0.72
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- def _pick_issuing_agency(lines: List[str]) -> Optional[str]:
86
- for line in lines[:12]:
87
- if line in AGENCY_SKIP:
88
- continue
89
- if _is_upper_like(line) and not NUMBER_RE.match(line) and "Hà Nội" not in line:
90
- return line
91
- return None
92
 
 
 
 
 
 
 
 
 
93
 
94
- def _pick_doc_number(lines: List[str]) -> Optional[str]:
95
- for line in lines[:25]:
96
- m = NUMBER_RE.match(line)
97
  if m:
98
  cleaned = _clean_doc_number(m.group(1))
99
  if cleaned:
100
  return cleaned
101
- return _norm_space(m.group(1))
102
- for line in lines[:25]:
103
- cleaned = _clean_doc_number(line)
104
- if cleaned:
105
- return cleaned
106
- return None
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- def _pick_date(lines: List[str]) -> tuple[Optional[str], Optional[int]]:
110
- for line in lines[:25]:
111
  m = DATE_RE.search(line)
112
  if m:
113
  day = int(m.group("day"))
114
  month = int(m.group("month"))
115
  year = int(m.group("year"))
116
- return f"{day:02d}/{month:02d}/{year:04d}", year
117
- return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
 
120
- def _find_doc_type(lines: List[str]) -> tuple[Optional[str], Optional[int]]:
121
- for idx, line in enumerate(lines[:40]):
122
- clean = _norm_space(line).upper()
123
- for doc_type in DOC_TYPES:
124
- if clean == doc_type:
125
- return doc_type, idx
126
- return None, None
127
 
 
 
 
128
 
129
- def _is_title_stop(line: str) -> bool:
130
- return any(p.search(line) for p in STOP_TITLE_PATTERNS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
 
133
  @dataclass
134
  class DocumentHeader:
135
  doc_id: str
136
  file_stem: str
137
- issuing_agency: Optional[str]
138
- doc_number: Optional[str]
139
- doc_type: Optional[str]
140
- official_title: Optional[str]
141
- title_block: str
142
- lead_block: str
143
- date_raw: Optional[str]
144
- year: Optional[int]
145
- body_start_index: int
 
 
 
146
 
147
  def to_metadata(self) -> Dict[str, object]:
148
  data = asdict(self)
@@ -154,97 +334,52 @@ class DocumentHeader:
154
 
155
  def extract_document_header(text: str, *, fallback_name: str = "") -> DocumentHeader:
156
  lines = _clean_lines(text)
157
- file_stem = fallback_name or "document"
158
- issuing_agency = _pick_issuing_agency(lines)
159
- doc_number = _pick_doc_number(lines)
160
- date_raw, year = _pick_date(lines)
161
- doc_type, doc_type_idx = _find_doc_type(lines)
162
 
163
- title_lines: List[str] = []
164
- title_start = None
165
- body_start_index = 0
166
-
167
- if doc_type_idx is not None:
168
- title_start = doc_type_idx
169
- title_lines.append(lines[doc_type_idx])
170
- for idx in range(doc_type_idx + 1, min(len(lines), doc_type_idx + 10)):
171
- line = lines[idx]
172
- if _is_title_stop(line):
173
- body_start_index = idx
174
- break
175
- if _is_upper_like(line) or line.upper().startswith("VỀ VIỆC"):
176
- title_lines.append(line)
177
- continue
178
- body_start_index = idx
179
- break
180
- else:
181
- body_start_index = min(len(lines), doc_type_idx + len(title_lines))
182
-
183
- if not title_lines:
184
- # fallback: lấy block upper-case dài nhất gần đầu file
185
- best_block: List[str] = []
186
- current: List[str] = []
187
- current_start = 0
188
- for idx, line in enumerate(lines[:30]):
189
- if _is_upper_like(line):
190
- if not current:
191
- current_start = idx
192
- current.append(line)
193
- else:
194
- if len(" ".join(current)) > len(" ".join(best_block)):
195
- best_block = current[:]
196
- title_start = current_start
197
- current = []
198
- if len(" ".join(current)) > len(" ".join(best_block)):
199
- best_block = current[:]
200
- title_start = current_start
201
- title_lines = best_block[:3]
202
- body_start_index = (title_start or 0) + len(title_lines)
203
- if title_lines and title_lines[0] in DOC_TYPES:
204
- doc_type = title_lines[0]
205
-
206
- title_block = "\n".join(title_lines).strip()
207
- official_title = None
208
- if title_lines:
209
- if doc_type and title_lines[0].upper() == doc_type:
210
- official_title = " ".join(title_lines[1:]).strip() or title_lines[0]
211
- else:
212
- official_title = " ".join(title_lines).strip()
213
 
214
  lead_lines: List[str] = []
215
- if body_start_index < len(lines):
216
- for idx in range(body_start_index, min(len(lines), body_start_index + 12)):
217
- line = lines[idx]
218
- if ARTICLE_START_RE.match(line) or ITEM_START_RE.match(line) or POINT_START_RE.match(line):
219
- body_start_index = idx
220
- break
 
 
 
 
 
 
221
  lead_lines.append(line)
222
- if len(" ".join(lead_lines)) >= 900:
223
- body_start_index = idx + 1
224
- break
225
- else:
226
- body_start_index = min(len(lines), body_start_index + len(lead_lines))
227
-
228
- lead_block = "\n".join(lead_lines[:6]).strip()
229
 
230
- if year is None and doc_number:
231
- m_year = re.search(r"/(\d{4})/", str(doc_number))
232
- if m_year:
233
- year = int(m_year.group(1))
234
 
235
- doc_id_seed = doc_number or official_title or file_stem
 
236
  doc_id = _slugify(doc_id_seed)
237
 
238
  return DocumentHeader(
239
  doc_id=doc_id,
240
  file_stem=file_stem,
241
- issuing_agency=issuing_agency,
242
- doc_number=doc_number,
243
  doc_type=doc_type,
 
 
 
244
  official_title=official_title,
 
245
  title_block=title_block,
246
  lead_block=lead_block,
247
  date_raw=date_raw,
248
- year=year,
 
249
  body_start_index=body_start_index,
250
  )
 
2
 
3
  import re
4
  from dataclasses import dataclass, asdict
5
+ from typing import Dict, List, Optional, Tuple
6
 
7
  DOC_TYPES = [
8
  "BỘ LUẬT",
 
20
  "ĐỀ ÁN",
21
  ]
22
 
23
+ TITLE_STOP_PATTERNS = [
24
+ re.compile(r"^Căn cứ\b", re.IGNORECASE),
25
+ re.compile(r"^Theo đề nghị\b", re.IGNORECASE),
26
+ re.compile(r"^Xét\b", re.IGNORECASE),
27
  re.compile(r"^Điều\s+\d+", re.IGNORECASE),
28
+ re.compile(r"^Chương\s+[IVXLC\d]+", re.IGNORECASE),
29
+ re.compile(r"^Mục\s+\d+", re.IGNORECASE),
30
+ re.compile(r"^Phần\s+[IVXLC\d]+", re.IGNORECASE),
31
  re.compile(r"^\d+\.\s+"),
32
  re.compile(r"^[a-zđ]\)\s+", re.IGNORECASE),
33
  ]
34
 
35
+ AGENCY_SKIP_EXACT = {
36
  "CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM",
37
  "Độc lập - Tự do - Hạnh phúc",
38
+ "ĐỘC LẬP - TỰ DO - HẠNH PHÚC",
39
+ "-------",
40
+ "---------------",
41
+ "---",
42
+ "|",
43
+ }
44
+
45
+ NUMBER_LINE_RE = re.compile(r"^\s*Số\s*:?\s*(.+?)\s*$", re.IGNORECASE)
46
+ STRICT_DOC_NUMBER_RE = re.compile(r"\b\d{1,4}\s*/\s*\d{4}\s*/\s*[A-ZĐ\-]+\b", re.IGNORECASE)
47
  DATE_RE = re.compile(
48
+ r"(?:(?P<place>[A-ZÀ-Ỵa-zà-ỵ\s\.\-]+)\s*,\s*)?ngày\s*(?P<day>\d{1,2})\s*tháng\s*(?P<month>\d{1,2})\s*năm\s*(?P<year>\d{4})",
49
  re.IGNORECASE,
50
  )
51
+ DATE_SLASH_RE = re.compile(r"\b(?P<day>\d{1,2})/(?P<month>\d{1,2})/(?P<year>\d{4})\b")
52
  ARTICLE_START_RE = re.compile(r"^Điều\s+\d+", re.IGNORECASE)
53
+ CHAPTER_START_RE = re.compile(r"^Chương\s+[IVXLC\d]+", re.IGNORECASE)
54
  ITEM_START_RE = re.compile(r"^\d+\.\s+")
55
  POINT_START_RE = re.compile(r"^[a-zđ]\)\s+", re.IGNORECASE)
56
 
57
+ # Hỗ trợ tên file kiểu:
58
+ # 01_2026_TT-NHNN_697839
59
+ # 04_2026_TT-BYT_123456
60
+ # 01_2026_QD-UBND_999999
61
+ FILENAME_DOC_NUMBER_FULL_RE = re.compile(
62
+ r"(?i)(?<![A-Z0-9Đ])(?P<num>\d{1,4})_(?:(?P<year>\d{4})_)?(?P<code>[A-ZĐ]{1,6}(?:-[A-ZĐ0-9]{1,20})+)(?:_[0-9]+)?(?![A-Z0-9Đ])"
63
+ )
64
+
65
+ TITLE_ROLE_STOP_RE = re.compile(
66
+ r"^(BỘ TRƯỞNG|THỨ TRƯỞNG|THỐNG ĐỐC|PHÓ THỐNG ĐỐC|CHỦ TỊCH|PHÓ CHỦ TỊCH|CỤC TRƯỞNG|PHÓ CỤC TRƯỞNG|VIỆN TRƯỞNG|CHÁNH ÁN|TỔNG KIỂM TOÁN)\b",
67
+ re.IGNORECASE,
68
+ )
69
+
70
+ AGENCY_LINE_RE = re.compile(
71
+ r"^(NGÂN HÀNG NHÀ NƯỚC|HỘI ĐỒNG NHÂN DÂN|ỦY BAN NHÂN DÂN|TÒA ÁN NHÂN DÂN|VIỆN KIỂM SÁT|KIỂM TOÁN NHÀ NƯỚC|BỘ\b|CHÍNH PHỦ\b|THỦ TƯỚNG\b)",
72
+ re.IGNORECASE,
73
+ )
74
+
75
 
76
  def _norm_space(text: str) -> str:
77
+ return " ".join((text or "").replace("\ufeff", " ").split()).strip()
78
 
79
 
80
  def _slugify(text: str) -> str:
81
  raw = _norm_space(text).lower()
82
  raw = re.sub(r"[^a-z0-9à-ỹ]+", "_", raw)
83
  raw = re.sub(r"_+", "_", raw).strip("_")
84
+ return raw or "document"
85
 
86
 
87
  def _clean_lines(text: str) -> List[str]:
88
  out: List[str] = []
89
  for raw in str(text or "").splitlines():
90
+ line = _norm_space(raw)
 
91
  if line:
92
  out.append(line)
93
  return out
94
 
95
 
96
+ def _is_upper_like(text: str) -> bool:
97
+ raw = _norm_space(text)
98
+ letters = [ch for ch in raw if ch.isalpha()]
99
+ if len(letters) < 4:
100
+ return False
101
+ uppers = sum(1 for ch in letters if ch.isupper())
102
+ return uppers / max(1, len(letters)) >= 0.72
103
+
104
+
105
+ def _looks_like_doc_type(line: str) -> bool:
106
+ return _norm_space(line).upper() in DOC_TYPES
107
+
108
+
109
+ def _clean_doc_number(text: str) -> str:
110
  raw = _norm_space(str(text or ""))
111
  if not raw:
112
+ return ""
113
+ m = STRICT_DOC_NUMBER_RE.search(raw.upper())
114
  if not m:
115
+ return ""
116
+ val = m.group(0).upper()
117
+ val = re.sub(r"\s*/\s*", "/", val)
118
+ val = re.sub(r"\s+", "", val)
119
+ return val
120
 
121
 
122
+ def _doc_number_from_filename(fallback_name: str) -> str:
123
+ fb = _norm_space(fallback_name).upper()
124
+ if not fb:
125
+ return ""
 
 
126
 
127
+ m = FILENAME_DOC_NUMBER_FULL_RE.search(fb)
128
+ if not m:
129
+ return ""
130
+
131
+ num = str(int(m.group("num")))
132
+ year = (m.group("year") or "").strip()
133
+ code = (m.group("code") or "").upper().strip()
134
+
135
+ if year:
136
+ return f"{num}/{year}/{code}"
137
+ return f"{num}/{code}"
138
+
139
+
140
+ def _find_doc_type(lines: List[str]) -> Tuple[str, Optional[int]]:
141
+ for idx, line in enumerate(lines[:20]):
142
+ up = _norm_space(line).upper()
143
+ if up in DOC_TYPES:
144
+ return up.title(), idx
145
+ return "", None
146
 
 
 
 
 
 
 
 
147
 
148
+ def _pick_doc_number(lines: List[str], fallback_name: str = "") -> str:
149
+ # 1) ưu tiên bắt ở đầu file
150
+ for line in lines[:50]:
151
+ m = NUMBER_LINE_RE.match(line)
152
+ if m:
153
+ cleaned = _clean_doc_number(m.group(1))
154
+ if cleaned:
155
+ return cleaned
156
 
157
+ # 2) quét toàn file để bắt case số hiệu nằm cuối văn bản
158
+ for line in lines:
159
+ m = NUMBER_LINE_RE.match(line)
160
  if m:
161
  cleaned = _clean_doc_number(m.group(1))
162
  if cleaned:
163
  return cleaned
 
 
 
 
 
 
164
 
165
+ # 3) fallback từ tên file
166
+ return _doc_number_from_filename(fallback_name)
167
+
168
+
169
+ def _pick_date(lines: List[str], fallback_name: str = "") -> Tuple[str, int, str]:
170
+ # 1) ưu tiên bắt ngày ở đầu file
171
+ for line in lines[:60]:
172
+ m = DATE_RE.search(line)
173
+ if m:
174
+ day = int(m.group("day"))
175
+ month = int(m.group("month"))
176
+ year = int(m.group("year"))
177
+ place = _norm_space(m.group("place") or "")
178
+ return f"{day:02d}/{month:02d}/{year:04d}", year, place
179
 
180
+ # 2) quét ngược toàn file để bắt case ngày nằm cuối văn bản
181
+ for line in reversed(lines):
182
  m = DATE_RE.search(line)
183
  if m:
184
  day = int(m.group("day"))
185
  month = int(m.group("month"))
186
  year = int(m.group("year"))
187
+ place = _norm_space(m.group("place") or "")
188
+ return f"{day:02d}/{month:02d}/{year:04d}", year, place
189
+
190
+ # 3) fallback kiểu dd/mm/yyyy trong file
191
+ for line in reversed(lines):
192
+ m = DATE_SLASH_RE.search(line)
193
+ if m:
194
+ day = int(m.group("day"))
195
+ month = int(m.group("month"))
196
+ year = int(m.group("year"))
197
+ return f"{day:02d}/{month:02d}/{year:04d}", year, ""
198
+
199
+ # 4) fallback từ tên file nếu có
200
+ fb = _norm_space(fallback_name)
201
+ m = DATE_SLASH_RE.search(fb)
202
+ if m:
203
+ day = int(m.group("day"))
204
+ month = int(m.group("month"))
205
+ year = int(m.group("year"))
206
+ return f"{day:02d}/{month:02d}/{year:04d}", year, ""
207
+
208
+ return "", 0, ""
209
 
210
 
211
+ def _pick_title_block(lines: List[str], doc_type_idx: Optional[int]) -> Tuple[str, str, int]:
212
+ if doc_type_idx is None:
213
+ return "", "", 0
 
 
 
 
214
 
215
+ title_lines: List[str] = []
216
+ start = doc_type_idx + 1
217
+ body_start_index = start
218
 
219
+ for idx in range(start, min(len(lines), start + 12)):
220
+ line = _norm_space(lines[idx])
221
+ if not line:
222
+ continue
223
+
224
+ if any(p.search(line) for p in TITLE_STOP_PATTERNS):
225
+ body_start_index = idx
226
+ break
227
+
228
+ if NUMBER_LINE_RE.match(line) or DATE_RE.search(line) or DATE_SLASH_RE.search(line):
229
+ body_start_index = idx
230
+ break
231
+
232
+ if _is_upper_like(line) or line.upper().startswith("VỀ VIỆC"):
233
+ title_lines.append(line)
234
+ body_start_index = idx + 1
235
+ continue
236
+
237
+ body_start_index = idx
238
+ break
239
+
240
+ title_block = "\n".join(title_lines).strip()
241
+ official_title = " ".join(title_lines).strip()
242
+ return title_block, official_title, body_start_index
243
+
244
+
245
+ def _extract_agency_from_action_line(line: str) -> str:
246
+ raw = _norm_space(line)
247
+ m = re.match(
248
+ r"^(Bộ trưởng|Thủ tướng|Chủ tịch|Thống đốc|Chánh án|Viện trưởng|Tổng Kiểm toán)\b.*",
249
+ raw,
250
+ re.IGNORECASE,
251
+ )
252
+ if not m:
253
+ return ""
254
+
255
+ if raw.lower().startswith("thống đốc ngân hàng nhà nước"):
256
+ return "Thống đốc Ngân hàng Nhà nước Việt Nam"
257
+ return raw
258
+
259
+
260
+ def _looks_like_agency_line(line: str) -> bool:
261
+ raw = _norm_space(line)
262
+ if not raw:
263
+ return False
264
+ if raw in AGENCY_SKIP_EXACT:
265
+ return False
266
+ if _extract_agency_from_action_line(raw):
267
+ return True
268
+ return bool(AGENCY_LINE_RE.match(raw))
269
+
270
+
271
+ def _pick_issuing_agency(lines: List[str], doc_type_idx: Optional[int], official_title: str) -> str:
272
+ official_title_up = _norm_space(official_title).upper()
273
+
274
+ # Ưu tiên dòng kiểu "Thống đốc ... ban hành ..."
275
+ for line in lines[:80]:
276
+ cand = _extract_agency_from_action_line(line)
277
+ if cand:
278
+ cand_up = cand.upper()
279
+ if official_title_up and (cand_up == official_title_up or cand_up in official_title_up):
280
+ continue
281
+ return cand
282
+
283
+ search_end = doc_type_idx if doc_type_idx is not None else min(len(lines), 20)
284
+ head = lines[: max(0, search_end)]
285
+
286
+ agency_candidates: List[str] = []
287
+ for line in head[:12]:
288
+ clean = _norm_space(line)
289
+ if _looks_like_agency_line(clean):
290
+ agency_candidates.append(clean)
291
+ continue
292
+ if agency_candidates:
293
+ break
294
+
295
+ if not agency_candidates:
296
+ for line in lines[:30]:
297
+ clean = _norm_space(line)
298
+ if _looks_like_agency_line(clean):
299
+ agency_candidates.append(clean)
300
+
301
+ for cand in agency_candidates:
302
+ cand_up = cand.upper()
303
+ if official_title_up and (cand_up == official_title_up or cand_up in official_title_up):
304
+ continue
305
+ return cand
306
+
307
+ return ""
308
 
309
 
310
  @dataclass
311
  class DocumentHeader:
312
  doc_id: str
313
  file_stem: str
314
+ doc_type: str = ""
315
+ law_type: str = ""
316
+ doc_number: str = ""
317
+ issuing_agency: str = ""
318
+ official_title: str = ""
319
+ law_name: str = ""
320
+ title_block: str = ""
321
+ lead_block: str = ""
322
+ date_raw: str = ""
323
+ year: int = 0
324
+ place: str = ""
325
+ body_start_index: int = 0
326
 
327
  def to_metadata(self) -> Dict[str, object]:
328
  data = asdict(self)
 
334
 
335
  def extract_document_header(text: str, *, fallback_name: str = "") -> DocumentHeader:
336
  lines = _clean_lines(text)
337
+ file_stem = _slugify(fallback_name or "document")
 
 
 
 
338
 
339
+ doc_type, doc_type_idx = _find_doc_type(lines)
340
+ doc_number = _pick_doc_number(lines, fallback_name=fallback_name)
341
+ date_raw, year, place = _pick_date(lines, fallback_name=fallback_name)
342
+ title_block, official_title, body_start_index = _pick_title_block(lines, doc_type_idx)
343
+ issuing_agency = _pick_issuing_agency(lines, doc_type_idx, official_title)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
 
345
  lead_lines: List[str] = []
346
+ if body_start_index > 0:
347
+ start = (doc_type_idx + 1) if doc_type_idx is not None else 0
348
+ for idx in range(start, min(body_start_index, start + 8)):
349
+ line = _norm_space(lines[idx])
350
+ if not line:
351
+ continue
352
+ if title_block and line in title_block:
353
+ continue
354
+ if NUMBER_LINE_RE.match(line) or DATE_RE.search(line) or DATE_SLASH_RE.search(line):
355
+ continue
356
+ if TITLE_ROLE_STOP_RE.match(line):
357
+ continue
358
  lead_lines.append(line)
359
+ lead_block = "\n".join(lead_lines).strip()
 
 
 
 
 
 
360
 
361
+ if not year and doc_number:
362
+ m = re.search(r"/(\d{4})/", doc_number)
363
+ if m:
364
+ year = int(m.group(1))
365
 
366
+ law_name = official_title or fallback_name or file_stem
367
+ doc_id_seed = doc_number or official_title or fallback_name or file_stem
368
  doc_id = _slugify(doc_id_seed)
369
 
370
  return DocumentHeader(
371
  doc_id=doc_id,
372
  file_stem=file_stem,
 
 
373
  doc_type=doc_type,
374
+ law_type=doc_type or "Unknown",
375
+ doc_number=doc_number,
376
+ issuing_agency=issuing_agency,
377
  official_title=official_title,
378
+ law_name=law_name,
379
  title_block=title_block,
380
  lead_block=lead_block,
381
  date_raw=date_raw,
382
+ year=year or 0,
383
+ place=place,
384
  body_start_index=body_start_index,
385
  )
src/rag/graph_builder.py CHANGED
@@ -1,262 +1,322 @@
1
  from __future__ import annotations
2
 
 
 
3
  from collections import defaultdict
4
- from typing import Any, Dict, List, Optional
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # =========================
8
- # Core utilities
9
- # =========================
10
 
11
  def _unique_dicts(items: List[Dict[str, Any]], keys: List[str]) -> List[Dict[str, Any]]:
12
  seen = set()
13
  out: List[Dict[str, Any]] = []
14
-
15
  for item in items:
16
  sig = tuple(str(item.get(k, "")).strip().lower() for k in keys)
17
  if sig in seen:
18
  continue
19
  seen.add(sig)
20
  out.append(item)
21
-
22
  return out
23
 
24
 
25
  def _index_nodes(nodes: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
26
- return {
27
- str(n["node_id"]): n
28
- for n in nodes
29
- if n.get("node_id")
30
- }
31
 
32
 
33
  def _build_adjacency(edges: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
34
  adj: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
35
-
36
  for e in edges:
37
- source_id = e.get("source_id")
38
- if source_id:
39
- adj[str(source_id)].append(e)
40
-
41
  return dict(adj)
42
 
43
 
44
  def _build_reverse_adjacency(edges: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
45
  rev: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
46
-
47
  for e in edges:
48
- target_id = e.get("target_id")
49
- if target_id:
50
- rev[str(target_id)].append(e)
51
-
52
  return dict(rev)
53
 
54
 
55
  def refresh_graph_indexes(graph: Dict[str, Any]) -> Dict[str, Any]:
56
- """
57
- Rebuild node_index / adjacency / reverse_adjacency
58
- after nodes or edges are updated.
59
- """
60
- nodes = list(graph.get("nodes", []))
61
- edges = list(graph.get("edges", []))
62
-
63
- graph["node_index"] = _index_nodes(nodes)
64
- graph["adjacency"] = _build_adjacency(edges)
65
- graph["reverse_adjacency"] = _build_reverse_adjacency(edges)
66
  return graph
67
 
68
 
69
- # =========================
70
- # Build graph
71
- # =========================
72
-
73
  def build_graph(
74
  graph_nodes: List[Dict[str, Any]],
75
  entity_nodes: Optional[List[Dict[str, Any]]] = None,
76
  summary_nodes: Optional[List[Dict[str, Any]]] = None,
77
  graph_edges: Optional[List[Dict[str, Any]]] = None,
78
  ) -> Dict[str, Any]:
79
- """
80
- Gom toàn bộ artifacts thành graph object chuẩn cho GraphRAG.
81
-
82
- Input:
83
- - graph_nodes: legal evidence nodes (article / clause / point / amendment / effective / ...)
84
- - entity_nodes: semantic/entity nodes
85
- - summary_nodes: summary nodes (có thể rỗng ở giai đoạn graph thô)
86
- - graph_edges: edges giữa các node
87
-
88
- Output:
89
- {
90
- "nodes": [...],
91
- "edges": [...],
92
- "node_index": {...},
93
- "adjacency": {...},
94
- "reverse_adjacency": {...}
95
- }
96
- """
97
  entity_nodes = entity_nodes or []
98
  summary_nodes = summary_nodes or []
99
  graph_edges = graph_edges or []
100
-
101
- all_nodes = list(graph_nodes) + list(entity_nodes) + list(summary_nodes)
102
- all_nodes = _unique_dicts(all_nodes, ["node_id"])
103
-
104
- graph_edges = _unique_dicts(
105
- graph_edges,
106
- [
107
- "source_id",
108
- "target_id",
109
- "relation_type",
110
- "source_text",
111
- "target_text",
112
- "target_article",
113
- "target_clause",
114
- "target_point",
115
- ],
116
- )
117
-
118
- graph = {
119
- "nodes": all_nodes,
120
- "edges": graph_edges,
121
- }
122
- graph = refresh_graph_indexes(graph)
123
- return graph
124
-
125
-
126
- # =========================
127
- # Entity co-occurrence edges
128
- # =========================
129
-
130
- def attach_entity_cooccurrence_edges(
131
- graph: Dict[str, Any],
132
- entities: List[Dict[str, Any]],
133
- ) -> Dict[str, Any]:
134
- """
135
- Nếu trong cùng 1 legal node có nhiều entities,
136
- tạo edge RELATED_IN_CONTEXT giữa các entity nodes.
137
- """
138
- edges = list(graph.get("edges", []))
139
-
140
- entities_by_source: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
141
- for ent in entities:
142
- node_id = ent.get("node_id")
143
- if node_id:
144
- entities_by_source[str(node_id)].append(ent)
145
-
146
- for source_node_id, ents in entities_by_source.items():
147
- entity_ids: List[str] = []
148
-
149
- for ent in ents:
150
- entity_type = ent.get("entity_type")
151
- entity_value = ent.get("entity_value")
152
- if entity_type and entity_value:
153
- entity_ids.append(
154
- f"entity::{entity_type}::{str(entity_value).strip().lower()}"
155
- )
156
-
157
- entity_ids = sorted(set(entity_ids))
158
-
159
- for i in range(len(entity_ids)):
160
- for j in range(i + 1, len(entity_ids)):
161
- e1 = entity_ids[i]
162
- e2 = entity_ids[j]
163
-
164
- edges.append(
165
- {
166
- "source_id": e1,
167
- "target_id": e2,
168
- "relation_type": "RELATED_IN_CONTEXT",
169
- }
170
- )
171
- edges.append(
172
- {
173
- "source_id": e2,
174
- "target_id": e1,
175
- "relation_type": "RELATED_IN_CONTEXT",
176
- }
177
- )
178
-
179
- graph["edges"] = _unique_dicts(
180
- edges,
181
- [
182
- "source_id",
183
- "target_id",
184
- "relation_type",
185
- "source_text",
186
- "target_text",
187
- "target_article",
188
- "target_clause",
189
- "target_point",
190
- ],
191
  )
 
192
  return refresh_graph_indexes(graph)
193
 
194
 
195
- # =========================
196
- # Main helper: ingestion -> graph
197
- # =========================
198
-
199
  def materialize_graph_from_ingestion(ingestion_output: Dict[str, Any]) -> Dict[str, Any]:
200
- """
201
- Helper chính để nối ingestion -> graph object.
202
-
203
- ingestion_output kỳ vọng có:
204
- {
205
- "graph_nodes": [...],
206
- "entity_nodes": [...],
207
- "summary_nodes": [...], # có thể rỗng
208
- "graph_edges": [...],
209
- "entities": [...]
210
- }
211
-
212
- Lưu ý:
213
- - graph_builder chỉ materialize graph thô
214
- - summary edges sẽ do hierachical_summary.py gắn sau
215
- """
216
  graph = build_graph(
217
  graph_nodes=ingestion_output.get("graph_nodes", []),
218
  entity_nodes=ingestion_output.get("entity_nodes", []),
219
  summary_nodes=ingestion_output.get("summary_nodes", []),
220
  graph_edges=ingestion_output.get("graph_edges", []),
221
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
- graph = attach_entity_cooccurrence_edges(
224
- graph=graph,
225
- entities=ingestion_output.get("entities", []),
226
- )
227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  return graph
229
 
230
 
231
- # =========================
232
- # Neighbor access
233
- # =========================
234
-
235
- def get_neighbors(
236
- graph: Dict[str, Any],
237
- node_id: str,
238
- relation_types: Optional[List[str]] = None,
239
- direction: str = "out",
240
- ) -> List[Dict[str, Any]]:
241
- """
242
- Lấy neighbors của 1 node.
243
-
244
- direction:
245
- - "out": source_id -> target_id
246
- - "in": target_id <- source_id
247
- """
248
- relation_types = relation_types or []
249
-
250
- if direction == "in":
251
- candidate_edges = graph.get("reverse_adjacency", {}).get(node_id, [])
252
- else:
253
- candidate_edges = graph.get("adjacency", {}).get(node_id, [])
254
-
255
- if not relation_types:
256
- return candidate_edges
257
-
258
- allowed = {x.upper() for x in relation_types}
259
- return [
260
- e for e in candidate_edges
261
- if str(e.get("relation_type", "")).upper() in allowed
262
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import json
4
+ import logging
5
  from collections import defaultdict
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional, Set, Tuple
8
 
9
+ from src.app.settings import settings
10
+ from src.rag.chunking_legal import legal_chunk
11
+ from src.rag.ingestion import ingest_document, upsert_chunks
12
+ from src.rag.legal_versioning import annotate_graph_with_versioning, build_evidence_ref_index, build_version_map
13
+ from src.storage.qdrant_store import ensure_collection, get_qdrant_client
14
+ from src.utils.loader import load_document
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ REFERENCE_NODE_TYPES_STRICT = {"article", "clause", "point"}
19
+ REFERENCE_NODE_TYPES_EXTENDED = REFERENCE_NODE_TYPES_STRICT | {"section", "item", "bullet"}
20
+
21
+
22
+ def _norm_space(text: str) -> str:
23
+ return " ".join((text or "").split()).strip()
24
 
 
 
 
25
 
26
  def _unique_dicts(items: List[Dict[str, Any]], keys: List[str]) -> List[Dict[str, Any]]:
27
  seen = set()
28
  out: List[Dict[str, Any]] = []
 
29
  for item in items:
30
  sig = tuple(str(item.get(k, "")).strip().lower() for k in keys)
31
  if sig in seen:
32
  continue
33
  seen.add(sig)
34
  out.append(item)
 
35
  return out
36
 
37
 
38
  def _index_nodes(nodes: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
39
+ return {str(n["node_id"]): n for n in nodes if n.get("node_id")}
 
 
 
 
40
 
41
 
42
  def _build_adjacency(edges: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
43
  adj: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
 
44
  for e in edges:
45
+ if e.get("source_id"):
46
+ adj[str(e["source_id"])].append(e)
 
 
47
  return dict(adj)
48
 
49
 
50
  def _build_reverse_adjacency(edges: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
51
  rev: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
 
52
  for e in edges:
53
+ if e.get("target_id"):
54
+ rev[str(e["target_id"])].append(e)
 
 
55
  return dict(rev)
56
 
57
 
58
  def refresh_graph_indexes(graph: Dict[str, Any]) -> Dict[str, Any]:
59
+ graph["node_index"] = _index_nodes(list(graph.get("nodes", [])))
60
+ graph["adjacency"] = _build_adjacency(list(graph.get("edges", [])))
61
+ graph["reverse_adjacency"] = _build_reverse_adjacency(list(graph.get("edges", [])))
 
 
 
 
 
 
 
62
  return graph
63
 
64
 
 
 
 
 
65
  def build_graph(
66
  graph_nodes: List[Dict[str, Any]],
67
  entity_nodes: Optional[List[Dict[str, Any]]] = None,
68
  summary_nodes: Optional[List[Dict[str, Any]]] = None,
69
  graph_edges: Optional[List[Dict[str, Any]]] = None,
70
  ) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  entity_nodes = entity_nodes or []
72
  summary_nodes = summary_nodes or []
73
  graph_edges = graph_edges or []
74
+ all_nodes = _unique_dicts(list(graph_nodes) + list(entity_nodes) + list(summary_nodes), ["node_id"])
75
+ all_edges = _unique_dicts(
76
+ list(graph_edges),
77
+ ["source_id", "target_id", "relation_type", "source_text", "target_text", "target_article", "target_clause", "target_point"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  )
79
+ graph = {"nodes": all_nodes, "edges": all_edges}
80
  return refresh_graph_indexes(graph)
81
 
82
 
 
 
 
 
83
  def materialize_graph_from_ingestion(ingestion_output: Dict[str, Any]) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  graph = build_graph(
85
  graph_nodes=ingestion_output.get("graph_nodes", []),
86
  entity_nodes=ingestion_output.get("entity_nodes", []),
87
  summary_nodes=ingestion_output.get("summary_nodes", []),
88
  graph_edges=ingestion_output.get("graph_edges", []),
89
  )
90
+ return refresh_graph_indexes(graph)
91
+
92
+
93
+ def _snapshot_path() -> Path:
94
+ p = Path(settings.graph_snapshot_path)
95
+ if not p.is_absolute():
96
+ p = Path.cwd() / p
97
+ return p
98
+
99
+
100
+ def _collect_node_children(node: Dict[str, Any]) -> List[str]:
101
+ md = dict(node.get("metadata") or {})
102
+ return [str(x) for x in (md.get("children_ids") or []) if str(x).strip()]
103
+
104
+
105
+ def _node_type(node: Dict[str, Any]) -> str:
106
+ md = dict(node.get("metadata") or {})
107
+ return str(node.get("node_type") or md.get("node_type") or "").strip().lower()
108
 
 
 
 
 
109
 
110
+ def _node_md(node: Dict[str, Any]) -> Dict[str, Any]:
111
+ return dict(node.get("metadata") or {})
112
+
113
+
114
+ def _is_reference_capable(node: Dict[str, Any]) -> bool:
115
+ node_type = _node_type(node)
116
+ children = _collect_node_children(node)
117
+ md = _node_md(node)
118
+ if node_type in REFERENCE_NODE_TYPES_STRICT:
119
+ return True
120
+ if node_type in REFERENCE_NODE_TYPES_EXTENDED and children:
121
+ return True
122
+ if children and (_norm_space(str(md.get("path_title") or "")) or _norm_space(str(node.get("text") or ""))):
123
+ return True
124
+ return False
125
+
126
+
127
+ def _is_section_anchor(node: Dict[str, Any]) -> bool:
128
+ node_type = _node_type(node)
129
+ return node_type in {"article", "clause", "point", "section", "item", "bullet"} and _is_reference_capable(node)
130
+
131
+
132
+ def _descendants(graph: Dict[str, Any], node_id: str) -> List[str]:
133
+ node_index = graph.get("node_index", {}) or {}
134
+ out: List[str] = []
135
+ seen: Set[str] = set()
136
+ queue = [node_id]
137
+ while queue:
138
+ cur = queue.pop(0)
139
+ node = node_index.get(cur)
140
+ if not node:
141
+ continue
142
+ children = _collect_node_children(node)
143
+ for child_id in children:
144
+ if child_id in seen:
145
+ continue
146
+ seen.add(child_id)
147
+ out.append(child_id)
148
+ queue.append(child_id)
149
+ return out
150
+
151
+
152
+ def collect_subtree_nodes(graph: Dict[str, Any], node_id: str) -> List[Dict[str, Any]]:
153
+ node_index = graph.get("node_index", {}) or {}
154
+ ids = [node_id] + _descendants(graph, node_id)
155
+ nodes = [node_index[nid] for nid in ids if nid in node_index]
156
+ nodes.sort(key=lambda n: int((_node_md(n).get("order_index") or 0)))
157
+ return nodes
158
+
159
+
160
+ def collect_subtree_text(graph: Dict[str, Any], node_id: str) -> str:
161
+ parts: List[str] = []
162
+ for node in collect_subtree_nodes(graph, node_id):
163
+ text = _norm_space(str(node.get("text") or ""))
164
+ if text:
165
+ parts.append(text)
166
+ return "\n".join(parts).strip()
167
+
168
+
169
+ def collect_amendment_source_nodes(graph: Dict[str, Any], node_id: str) -> List[Dict[str, Any]]:
170
+ reverse_adj = graph.get("reverse_adjacency", {}) or {}
171
+ node_index = graph.get("node_index", {}) or {}
172
+ out: List[Dict[str, Any]] = []
173
+ seen: Set[str] = set()
174
+ for edge in reverse_adj.get(node_id, []):
175
+ rel = str(edge.get("relation_type") or "").upper()
176
+ if rel not in {"AMENDS", "REPEALS", "REPLACES", "PARTIALLY_AMENDS", "PARTIALLY_REPEALS"}:
177
+ continue
178
+ src = str(edge.get("source_id") or "")
179
+ if not src or src in seen or src not in node_index:
180
+ continue
181
+ seen.add(src)
182
+ out.append(node_index[src])
183
+ return out
184
+
185
+
186
+ def _build_doc_index(graph: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
187
+ node_index = graph.get("node_index", {}) or {}
188
+ docs: Dict[str, Dict[str, Any]] = {}
189
+ for node_id, node in node_index.items():
190
+ md = _node_md(node)
191
+ doc_id = str(md.get("doc_id") or "").strip()
192
+ if not doc_id:
193
+ continue
194
+ doc = docs.setdefault(
195
+ doc_id,
196
+ {
197
+ "id": doc_id,
198
+ "doc_id": doc_id,
199
+ "official_title": str(md.get("official_title") or md.get("law_name") or "").strip(),
200
+ "doc_sketch": "",
201
+ "law_name": str(md.get("law_name") or md.get("official_title") or "").strip(),
202
+ "law_type": str(md.get("law_type") or md.get("doc_type") or "Unknown"),
203
+ "doc_type": str(md.get("doc_type") or md.get("law_type") or "Unknown"),
204
+ "source": str(md.get("source") or md.get("issuing_agency") or "LocalFile"),
205
+ "issuing_agency": str(md.get("issuing_agency") or md.get("source") or "").strip(),
206
+ "year": int(md.get("year") or 0),
207
+ "date_raw": str(md.get("date_raw") or "").strip(),
208
+ "doc_number": str(md.get("doc_number") or "").strip(),
209
+ "reference_node_ids_strict": [],
210
+ "reference_node_ids": [],
211
+ "evidence_node_ids": [],
212
+ "member_node_ids": [],
213
+ "doc_sketch_node_id": "",
214
+ },
215
+ )
216
+ artifact = str(md.get("artifact_type") or "evidence")
217
+ if artifact == "doc_sketch":
218
+ doc["doc_sketch"] = str(node.get("text") or md.get("retrieval_text") or "")
219
+ doc["doc_sketch_node_id"] = node_id
220
+ elif artifact in {"evidence", "article_bundle"}:
221
+ doc["evidence_node_ids"].append(node_id)
222
+ if _is_reference_capable(node):
223
+ doc["reference_node_ids"].append(node_id)
224
+ if _node_type(node) in REFERENCE_NODE_TYPES_STRICT:
225
+ doc["reference_node_ids_strict"].append(node_id)
226
+ doc["member_node_ids"].append(node_id)
227
+
228
+ for doc in docs.values():
229
+ for key in ["reference_node_ids_strict", "reference_node_ids", "evidence_node_ids", "member_node_ids"]:
230
+ seen: Set[str] = set()
231
+ cleaned: List[str] = []
232
+ for nid in doc[key]:
233
+ if nid in seen:
234
+ continue
235
+ seen.add(nid)
236
+ cleaned.append(nid)
237
+ doc[key] = cleaned
238
+ return docs
239
+
240
+
241
+ def finalize_graph(graph: Dict[str, Any]) -> Dict[str, Any]:
242
+ graph = refresh_graph_indexes(graph)
243
+ graph = annotate_graph_with_versioning(graph)
244
+ graph = refresh_graph_indexes(graph)
245
+ graph["doc_index"] = _build_doc_index(graph)
246
+ graph["evidence_ref_index"] = build_evidence_ref_index(graph)
247
+ graph["version_map"] = build_version_map(graph)
248
  return graph
249
 
250
 
251
+ def build_runtime_graph(*, input_dir: Optional[str] = None, glob_pattern: Optional[str] = None) -> Dict[str, Any]:
252
+ base = Path(input_dir or settings.normalized_dir)
253
+ pattern = glob_pattern or settings.normalized_glob
254
+ if not base.exists():
255
+ raise RuntimeError(f"Missing normalized dir: {base}")
256
+
257
+ all_nodes: List[Dict[str, Any]] = []
258
+ all_edges: List[Dict[str, Any]] = []
259
+ for fp in sorted(base.glob(pattern)):
260
+ if fp.suffix.lower() not in {".txt", ".pdf", ".doc", ".docx"}:
261
+ continue
262
+ text = load_document(fp)
263
+ out = ingest_document(text, fallback_doc_name=fp.stem)
264
+ all_nodes.extend(out.get("graph_nodes", []))
265
+ all_edges.extend(out.get("graph_edges", []))
266
+
267
+ graph = build_graph(graph_nodes=all_nodes, graph_edges=all_edges)
268
+ return finalize_graph(graph)
269
+
270
+
271
+ def save_graph_snapshot(graph: Dict[str, Any]) -> Path:
272
+ p = _snapshot_path()
273
+ p.parent.mkdir(parents=True, exist_ok=True)
274
+ payload = {
275
+ "nodes": list(graph.get("nodes", [])),
276
+ "edges": list(graph.get("edges", [])),
277
+ }
278
+ p.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
279
+ return p
280
+
281
+
282
+ def load_graph_snapshot() -> Optional[Dict[str, Any]]:
283
+ p = _snapshot_path()
284
+ if not p.exists():
285
+ return None
286
+ try:
287
+ raw = json.loads(p.read_text(encoding="utf-8"))
288
+ except Exception as exc:
289
+ logger.warning("Failed to load graph snapshot: %s", exc)
290
+ return None
291
+ graph = build_graph(graph_nodes=list(raw.get("nodes", [])), graph_edges=list(raw.get("edges", [])))
292
+ return finalize_graph(graph)
293
+
294
+
295
+ def reindex_qdrant_from_normalized(*, input_dir: Optional[str] = None, glob_pattern: Optional[str] = None) -> Dict[str, Any]:
296
+ base = Path(input_dir or settings.normalized_dir)
297
+ pattern = glob_pattern or settings.normalized_glob
298
+ if not base.exists():
299
+ raise RuntimeError(f"Missing normalized dir: {base}")
300
+ client = get_qdrant_client()
301
+ ensure_collection(client)
302
+ total = 0
303
+ for fp in sorted(base.glob(pattern)):
304
+ if fp.suffix.lower() not in {".txt", ".pdf", ".doc", ".docx"}:
305
+ continue
306
+ text = load_document(fp)
307
+ chunks = legal_chunk(text, fallback_doc_name=fp.stem)
308
+ total += upsert_chunks(chunks)
309
+ return {"status": "ok", "indexed_chunks": total}
310
+
311
+
312
+ def rebuild_everything(*, input_dir: Optional[str] = None, glob_pattern: Optional[str] = None) -> Dict[str, Any]:
313
+ reindex_result = reindex_qdrant_from_normalized(input_dir=input_dir, glob_pattern=glob_pattern)
314
+ graph = build_runtime_graph(input_dir=input_dir, glob_pattern=glob_pattern)
315
+ snapshot = save_graph_snapshot(graph)
316
+ return {
317
+ "status": "ok",
318
+ "indexed_chunks": reindex_result.get("indexed_chunks", 0),
319
+ "graph_nodes": len(graph.get("nodes", [])),
320
+ "graph_edges": len(graph.get("edges", [])),
321
+ "snapshot_path": str(snapshot),
322
+ }
src/rag/hybrid.py CHANGED
@@ -2,15 +2,22 @@ from __future__ import annotations
2
 
3
  import math
4
  import re
5
- from typing import Any, Dict, List, Optional, Tuple
 
6
 
7
- # Unicode-aware tokenizer for Vietnamese legal text.
8
  TOKEN_RE = re.compile(r"\w+", re.UNICODE)
9
  ARTICLE_RE = re.compile(r"điều\s+(\d+)", re.IGNORECASE)
10
  CLAUSE_RE = re.compile(r"khoản\s+(\d+)", re.IGNORECASE)
11
  POINT_RE = re.compile(r"điểm\s+([a-zđ])", re.IGNORECASE)
12
 
13
 
 
 
 
 
 
 
 
14
  def _norm_space(text: str) -> str:
15
  return " ".join((text or "").split()).strip()
16
 
@@ -18,26 +25,59 @@ def _norm_space(text: str) -> str:
18
  def _legal_reference_tokens(text: str) -> List[str]:
19
  raw = _norm_space((text or "").lower())
20
  extra: List[str] = []
21
-
22
  for m in ARTICLE_RE.finditer(raw):
23
  num = m.group(1)
24
  extra.extend([f"điều_{num}", f"article_{num}"])
25
-
26
  for m in CLAUSE_RE.finditer(raw):
27
  num = m.group(1)
28
  extra.extend([f"khoản_{num}", f"clause_{num}"])
29
-
30
  for m in POINT_RE.finditer(raw):
31
  ch = m.group(1).lower()
32
  extra.extend([f"điểm_{ch}", f"point_{ch}"])
33
-
34
  return extra
35
 
36
 
 
 
 
 
 
 
37
  def tokenize(text: str) -> List[str]:
38
  raw = _norm_space(text).lower()
39
  base = [tok for tok in TOKEN_RE.findall(raw) if tok.strip()]
40
- return base + _legal_reference_tokens(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
 
43
  def bm25_score(
@@ -51,26 +91,19 @@ def bm25_score(
51
  ) -> float:
52
  if not query_tokens or not doc_tokens:
53
  return 0.0
54
-
55
- tf: Dict[str, int] = {}
56
- for tok in doc_tokens:
57
- tf[tok] = tf.get(tok, 0) + 1
58
-
59
  doc_len = max(len(doc_tokens), 1)
60
  avgdl_eff = max(float(avgdl or 0.0), 1.0)
61
  score = 0.0
62
-
63
  for q in query_tokens:
64
  freq = tf.get(q, 0)
65
  if freq <= 0:
66
  continue
67
-
68
  idf = float((idf_map or {}).get(q, 1.0))
69
  denom = freq + k1 * (1.0 - b + b * (doc_len / avgdl_eff))
70
  if denom <= 0:
71
  continue
72
  score += idf * (freq * (k1 + 1.0)) / denom
73
-
74
  return float(score)
75
 
76
 
@@ -84,52 +117,28 @@ def _minmax(values: List[float]) -> List[float]:
84
  return [(v - lo) / (hi - lo) for v in values]
85
 
86
 
87
- def hybrid_rank(
88
- question: str,
89
- candidates: List[Dict[str, Any]],
90
- *,
91
- dense_key: str = "dense_score",
92
- text_key: str = "retrieval_text",
93
- alpha: float = 0.55,
94
- idf_map: Optional[Dict[str, float]] = None,
95
- avgdl: float = 0.0,
96
- ) -> List[Tuple[float, Dict[str, Any]]]:
97
- if not candidates:
98
- return []
99
 
100
- q_tokens = tokenize(question)
101
-
102
- dense_values: List[float] = []
103
- bm25_values: List[float] = []
104
- enriched: List[Dict[str, Any]] = []
105
-
106
- for cand in candidates:
107
- item = dict(cand)
108
- dense = float(item.get(dense_key, 0.0) or 0.0)
109
- text = str(item.get(text_key) or item.get("text") or item.get("snippet") or "")
110
- tokens = tokenize(text)
111
- lex = bm25_score(
112
- q_tokens,
113
- tokens,
114
- idf_map=idf_map,
115
- avgdl=avgdl,
116
- )
117
- item["bm25_score"] = float(lex)
118
- dense_values.append(dense)
119
- bm25_values.append(float(lex))
120
- enriched.append(item)
121
 
122
- dense_norm = _minmax(dense_values)
 
 
123
  bm25_norm = _minmax(bm25_values)
124
-
125
- ranked: List[Tuple[float, Dict[str, Any]]] = []
126
- for idx, item in enumerate(enriched):
127
- dense_n = dense_norm[idx] if idx < len(dense_norm) else 0.0
128
- bm25_n = bm25_norm[idx] if idx < len(bm25_norm) else 0.0
129
- score = alpha * dense_n + (1.0 - alpha) * bm25_n
130
- item["dense_norm"] = float(dense_n)
131
- item["bm25_norm"] = float(bm25_n)
132
- ranked.append((float(score), item))
133
-
134
- ranked.sort(key=lambda x: x[0], reverse=True)
135
- return ranked
 
 
2
 
3
  import math
4
  import re
5
+ from collections import Counter
6
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
7
 
 
8
  TOKEN_RE = re.compile(r"\w+", re.UNICODE)
9
  ARTICLE_RE = re.compile(r"điều\s+(\d+)", re.IGNORECASE)
10
  CLAUSE_RE = re.compile(r"khoản\s+(\d+)", re.IGNORECASE)
11
  POINT_RE = re.compile(r"điểm\s+([a-zđ])", re.IGNORECASE)
12
 
13
 
14
+ TOPIC_PHRASE_MIN_TOKEN_LEN = 2
15
+ STOPWORDS = {
16
+ "và", "của", "các", "những", "trong", "trước", "sau", "cho", "về", "việc", "để", "tại", "theo",
17
+ "là", "ở", "có", "khi", "này", "đó", "với", "một", "nhiều", "được", "đang", "cần",
18
+ }
19
+
20
+
21
  def _norm_space(text: str) -> str:
22
  return " ".join((text or "").split()).strip()
23
 
 
25
  def _legal_reference_tokens(text: str) -> List[str]:
26
  raw = _norm_space((text or "").lower())
27
  extra: List[str] = []
 
28
  for m in ARTICLE_RE.finditer(raw):
29
  num = m.group(1)
30
  extra.extend([f"điều_{num}", f"article_{num}"])
 
31
  for m in CLAUSE_RE.finditer(raw):
32
  num = m.group(1)
33
  extra.extend([f"khoản_{num}", f"clause_{num}"])
 
34
  for m in POINT_RE.finditer(raw):
35
  ch = m.group(1).lower()
36
  extra.extend([f"điểm_{ch}", f"point_{ch}"])
 
37
  return extra
38
 
39
 
40
+ def _ngrams(tokens: List[str], n: int) -> List[str]:
41
+ if len(tokens) < n:
42
+ return []
43
+ return [" ".join(tokens[i:i+n]) for i in range(len(tokens) - n + 1)]
44
+
45
+
46
  def tokenize(text: str) -> List[str]:
47
  raw = _norm_space(text).lower()
48
  base = [tok for tok in TOKEN_RE.findall(raw) if tok.strip()]
49
+ grams = _ngrams(base, 2) + _ngrams(base, 3)
50
+ return base + grams + _legal_reference_tokens(raw)
51
+
52
+
53
+ def extract_topic_phrases(question: str) -> List[str]:
54
+ tokens = [tok for tok in TOKEN_RE.findall(_norm_space(question).lower()) if tok.strip()]
55
+ out: List[str] = []
56
+ for n in (3, 2):
57
+ for gram in _ngrams(tokens, n):
58
+ parts = gram.split()
59
+ if all(p in STOPWORDS for p in parts):
60
+ continue
61
+ if len([p for p in parts if p not in STOPWORDS]) < TOPIC_PHRASE_MIN_TOKEN_LEN:
62
+ continue
63
+ out.append(gram)
64
+ seen = set()
65
+ uniq: List[str] = []
66
+ for item in out:
67
+ if item in seen:
68
+ continue
69
+ seen.add(item)
70
+ uniq.append(item)
71
+ return uniq
72
+
73
+
74
+ def phrase_overlap_score(question: str, text: str) -> Tuple[float, List[str]]:
75
+ phrases = extract_topic_phrases(question)
76
+ hay = _norm_space(text).lower()
77
+ hits = [p for p in phrases if p in hay]
78
+ if not phrases:
79
+ return 0.0, hits
80
+ return float(len(hits) / len(phrases)), hits
81
 
82
 
83
  def bm25_score(
 
91
  ) -> float:
92
  if not query_tokens or not doc_tokens:
93
  return 0.0
94
+ tf = Counter(doc_tokens)
 
 
 
 
95
  doc_len = max(len(doc_tokens), 1)
96
  avgdl_eff = max(float(avgdl or 0.0), 1.0)
97
  score = 0.0
 
98
  for q in query_tokens:
99
  freq = tf.get(q, 0)
100
  if freq <= 0:
101
  continue
 
102
  idf = float((idf_map or {}).get(q, 1.0))
103
  denom = freq + k1 * (1.0 - b + b * (doc_len / avgdl_eff))
104
  if denom <= 0:
105
  continue
106
  score += idf * (freq * (k1 + 1.0)) / denom
 
107
  return float(score)
108
 
109
 
 
117
  return [(v - lo) / (hi - lo) for v in values]
118
 
119
 
120
+ def rrf_merge(rank_lists: List[List[str]], *, k: int = 60) -> Dict[str, float]:
121
+ out: Dict[str, float] = {}
122
+ for rank_list in rank_lists:
123
+ for idx, item_id in enumerate(rank_list, start=1):
124
+ out[item_id] = out.get(item_id, 0.0) + 1.0 / (k + idx)
125
+ return out
 
 
 
 
 
 
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
+ def field_dense_bm25(question: str, texts: List[str], dense_scores: Optional[List[float]] = None) -> List[Dict[str, float]]:
129
+ q_tokens = tokenize(question)
130
+ bm25_values = [bm25_score(q_tokens, tokenize(text)) for text in texts]
131
  bm25_norm = _minmax(bm25_values)
132
+ dense_scores = dense_scores or [0.0] * len(texts)
133
+ dense_norm = _minmax([float(x or 0.0) for x in dense_scores])
134
+ out: List[Dict[str, float]] = []
135
+ for idx in range(len(texts)):
136
+ out.append(
137
+ {
138
+ "dense": float(dense_scores[idx] if idx < len(dense_scores) else 0.0),
139
+ "dense_norm": float(dense_norm[idx] if idx < len(dense_norm) else 0.0),
140
+ "bm25": float(bm25_values[idx]),
141
+ "bm25_norm": float(bm25_norm[idx] if idx < len(bm25_norm) else 0.0),
142
+ }
143
+ )
144
+ return out
src/rag/openai_clients.py CHANGED
@@ -55,5 +55,4 @@ def warmup_openai_clients() -> None:
55
 
56
 
57
  def get_embeding_dim(emb: OpenAIEmbeddings) -> int:
58
- v = emb.embed_query("dim_check")
59
- return len(v)
 
55
 
56
 
57
  def get_embeding_dim(emb: OpenAIEmbeddings) -> int:
58
+ return len(emb.embed_query("dim_check"))
 
src/rag/qa_engine.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  from collections import OrderedDict
4
  from typing import Any, Dict, List
5
 
@@ -12,41 +13,121 @@ from src.rag.schemas import ChatResponse, SourceItem
12
  BASE_SYSTEM_PROMPT = """
13
  Bạn là trợ lý trả lời pháp luật Việt Nam.
14
 
15
- Nguyên tắc:
16
- - Chỉ dựa trên ngữ cảnh đã truy xuất.
17
- - Trả lời đúng trọng tâm câu hỏi.
18
- - Nếu nguồn chưa đủ, nói rõ chưa đủ căn cứ.
19
- - Không suy diễn vượt quá ngữ cảnh.
20
- - Khi cần, nêu rõ căn cứ thuộc văn bản nào, điều/khoản/điểm nào.
 
21
  """.strip()
22
 
23
- ROUTE_EXTRA_PROMPTS = {
24
- "heading_list": "- Đây là câu hỏi kiểu liệt kê theo heading/phần/điều. Hãy tổng hợp đầy đủ các ý trong cùng điều, không kéo ý từ điều khác nếu không cùng căn cứ.",
25
- "version_change": "- Đây là câu hỏi về bãi bỏ/sửa đổi/bổ sung/thay thế/hiệu lực. Hãy xác định đúng văn bản hoặc nội dung bị tác động và nêu căn cứ cụ thể.",
26
- "direct_reference": "- Đây là câu hỏi tham chiếu trực tiếp. Hãy trả lời đúng ý được hỏi tại điều/khoản/điểm đó và hạn chế lan sang phần khác.",
27
- "condition_circumstance": "- Đây là câu hỏi về điều kiện/trường hợp. Hãy nêu rõ điều kiện hoặc trường hợp áp dụng, rồi dẫn căn cứ.",
28
- "factoid": "- Hãy ưu tiên đoạn nào trả lời trực tiếp nhất cho câu hỏi.",
29
- "document_focus": "- Người dùng đang hỏi xoay quanh một văn bản cụ thể. Hãy ưu tiên ngữ cảnh của đúng văn bản đó.",
30
- }
 
 
31
 
32
 
33
  def _norm_space(text: str) -> str:
34
  return " ".join((text or "").split()).strip()
35
 
36
 
37
- def _doc_key(metadata: Dict[str, Any]) -> str:
38
- return str(metadata.get("doc_id") or metadata.get("law_name") or metadata.get("official_title") or "unknown").strip().lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
 
40
 
41
- def _group_for_context(passages: List[Dict[str, Any]], max_items: int) -> List[Dict[str, Any]]:
 
42
  grouped: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()
43
- for p in passages[:max_items]:
 
44
  md = dict(p.get("metadata") or {})
45
- key = _doc_key(md)
 
46
  bucket = grouped.setdefault(
47
- key,
48
  {
49
- "doc_key": key,
50
  "doc_title": md.get("official_title") or md.get("law_name") or "unknown",
51
  "doc_type": md.get("doc_type") or md.get("law_type") or "Unknown",
52
  "source": md.get("source") or md.get("issuing_agency") or "LocalFile",
@@ -54,7 +135,10 @@ def _group_for_context(passages: List[Dict[str, Any]], max_items: int) -> List[D
54
  "doc_best_score": float(p.get("final_score", 0.0) or 0.0),
55
  },
56
  )
57
- bucket["doc_best_score"] = max(bucket["doc_best_score"], float(p.get("final_score", 0.0) or 0.0))
 
 
 
58
  bucket["items"].append(p)
59
 
60
  docs = list(grouped.values())
@@ -62,188 +146,128 @@ def _group_for_context(passages: List[Dict[str, Any]], max_items: int) -> List[D
62
  return docs
63
 
64
 
65
- def _dedup_blocks(texts: List[str]) -> List[str]:
66
- seen = set()
67
- out: List[str] = []
68
- for text in texts:
69
- block = _norm_space(text)
70
- if not block:
71
- continue
72
- key = block.lower()
73
- if key in seen:
74
- continue
75
- seen.add(key)
76
- out.append(block)
77
- return out
78
 
 
 
 
 
 
 
79
 
80
- def _build_context(passages: List[Dict[str, Any]], max_items: int) -> str:
81
- groups = _group_for_context(passages, max_items)
82
- lines: List[str] = []
83
- for idx, group in enumerate(groups, start=1):
84
- lines.append(f"[Nguồn {idx}] {group['doc_type']} | {group['doc_title']} | source={group['source']}")
85
- shared_blocks = _dedup_blocks([str(item.get("shared_text") or "") for item in group["items"]])
86
- if shared_blocks:
87
- lines.append("[Ngữ cảnh chung của văn bản]")
88
- for block in shared_blocks:
89
- lines.append(block)
90
- for j, item in enumerate(group["items"], start=1):
91
  md = dict(item.get("metadata") or {})
92
- lines.append(
93
- f" - [Passage {idx}.{j}] artifact={md.get('artifact_type') or '-'} | path={md.get('path_title') or '-'} | article={md.get('article') or '-'} | clause={md.get('clause') or '-'} | point={md.get('point') or '-'}"
 
 
94
  )
95
- local_text = str(item.get("local_text") or item.get("bundle_text") or item.get("retrieval_text") or item.get("text") or "")
96
- lines.append(f" {local_text}")
97
- lines.append("")
98
- return "\n".join(lines).strip()
99
-
100
 
101
- def _to_source_item(p: Dict[str, Any]) -> SourceItem:
102
- md = dict(p.get("metadata") or {})
103
- snippet = str(p.get("local_text") or p.get("bundle_text") or p.get("retrieval_text") or p.get("text") or p.get("snippet") or "")[:500]
104
- return SourceItem(
105
- chunk_id=str(md.get("chunk_id") or md.get("node_id") or p.get("node_id") or ""),
106
- law_name=str(md.get("official_title") or md.get("law_name") or ""),
107
- law_type=str(md.get("doc_type") or md.get("law_type") or "Unknown"),
108
- year=int(md.get("year") or 0),
109
- source=str(md.get("source") or md.get("issuing_agency") or ""),
110
- article=md.get("article"),
111
- snippet=snippet,
112
- )
113
 
 
 
 
 
 
 
114
 
115
- def _same_article_focus(passages: List[Dict[str, Any]]) -> bool:
116
- articles = {
117
- _norm_space(str((p.get("metadata") or {}).get("article") or ""))
118
- for p in passages
119
- if _norm_space(str((p.get("metadata") or {}).get("article") or ""))
120
- }
121
- return len(articles) == 1 and bool(articles)
122
 
 
123
 
124
- def _extract_doc_numbers(text: str) -> List[str]:
125
- import re
126
- seen = set()
127
- out: List[str] = []
128
- for m in re.finditer(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+\b", str(text or "").upper()):
129
- value = _norm_space(m.group(0)).upper()
130
- if value in seen:
131
- continue
132
- seen.add(value)
133
- out.append(value)
134
- return out
135
 
136
 
137
- def _build_no_passage_fallback(question: str, retrieval_result: Dict[str, Any], query_profile: Dict[str, Any]) -> str:
138
- route = str(query_profile.get("route") or "factoid")
139
- filters = retrieval_result.get("filters") or query_profile.get("filters") or {}
140
- seed_candidates = retrieval_result.get("seed_candidates") or []
141
- doc_seed_stage = str((query_profile.get("document_seed_stage") or "none")).strip()
142
 
143
- if route == "version_change" and seed_candidates:
144
- source_doc = str(filters.get("doc_number") or "").upper().strip()
145
- top = dict(seed_candidates[0] or {})
146
- text = "\n".join(
147
- str(top.get(k) or "") for k in ["title_block", "lead_block", "doc_sketch", "text", "law_name"]
148
- )
149
- candidates = [x for x in _extract_doc_numbers(text) if x and x != source_doc]
150
- if candidates:
151
- joined = ", ".join(candidates[:3])
152
- return (
153
- f"Tạm thời chưa trích được passage xác nhận, nhưng từ văn bản nguồn đã nhận diện được, văn bản bị tác động nhiều khả năng là {joined}. "
154
- f"Hệ thống đang dừng ở tầng retrieval nên nên kiểm tra lại pipeline document_seed[{doc_seed_stage}] và passage extraction."
 
 
 
 
155
  )
156
-
157
- if filters.get("doc_number") or filters.get("law_type"):
158
- bits = []
159
- if filters.get("law_type"):
160
- bits.append(str(filters.get("law_type")))
161
- if filters.get("doc_number"):
162
- bits.append(str(filters.get("doc_number")))
163
- target = " ".join(bits).strip()
164
- return (
165
- f"Hệ thống đã nhận diện truy vấn nhắm tới {target or 'một văn bản cụ thể'}, nhưng chưa lấy ra được passage phù hợp từ retrieval. "
166
- f"Tầng document seed hiện tại: {doc_seed_stage}."
167
  )
168
 
169
- return "Chưa tìm thấy ngữ cảnh phù hợp để trả lời câu hỏi này trong dữ liệu hiện có."
170
-
171
-
172
- def build_chat_response(
173
- question: str,
174
- passages: List[Dict[str, Any]],
175
- *,
176
- max_context_passages: int | None = None,
177
- max_source_items: int | None = None,
178
- response_mode: str | None = None,
179
- query_profile: Dict[str, Any] | None = None,
180
- retrieval_result: Dict[str, Any] | None = None,
181
- ) -> ChatResponse:
182
- _ = response_mode
183
- query_profile = query_profile or {}
184
- if not passages:
185
- answer = _build_no_passage_fallback(question, retrieval_result or {}, query_profile)
186
- return ChatResponse(answer=answer, sources=[])
187
 
188
- route = str(query_profile.get("route") or "factoid")
189
- max_context_passages = max_context_passages or settings.answer_max_context_passages
190
- max_source_items = max_source_items or settings.answer_max_source_items
191
- context = _build_context(passages, max_context_passages)
192
 
193
- route_extra = ROUTE_EXTRA_PROMPTS.get(route, "")
194
- same_article_hint = ""
195
- if route == "heading_list" and not _same_article_focus(passages):
196
- same_article_hint = "- Cảnh báo: ngữ cảnh đang có khả năng lẫn nhiều điều. Nếu chưa đủ chắc chắn cùng một điều, hãy nói rõ chưa đủ căn cứ."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
- prompt = f"""
199
- Câu hỏi người dùng:
200
  {question}
201
 
202
- Loại truy vấn:
203
- {route}
204
-
205
- Ngữ cảnh đã truy xuất:
206
  {context}
207
 
208
- Yêu cầu:
209
- - Trả lời trực tiếp và bám sát câu hỏi.
210
- - Ưu tiên nguồn nào sát nhất.
211
- - Nếu thiếu căn cứ thì nói rõ.
212
- {route_extra}
213
- {same_article_hint}
214
  """.strip()
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  llm = get_llm()
217
- response = llm.invoke([
218
- SystemMessage(content=BASE_SYSTEM_PROMPT),
219
- HumanMessage(content=prompt),
220
- ])
221
- answer = _norm_space(getattr(response, "content", "") or "")
 
 
 
222
  if not answer:
223
- answer = "Chưa tạo được câu trả lời từ ngữ cảnh đã truy xuất."
224
 
225
- sources: List[SourceItem] = []
226
- seen = set()
227
- for p in passages[:max_source_items]:
228
- src = _to_source_item(p)
229
- key = (src.chunk_id, src.source, src.article)
230
- if key in seen:
231
- continue
232
- seen.add(key)
233
- sources.append(src)
234
-
235
- return ChatResponse(answer=answer, sources=sources)
236
-
237
-
238
- def answer_with_rag(question: str, retrieval_result: Dict[str, Any], *, response_mode: str | None = None) -> ChatResponse:
239
- retrieval_result = retrieval_result or {}
240
- passages = retrieval_result.get("passages", []) or []
241
- return build_chat_response(
242
- question=question,
243
- passages=passages,
244
- max_context_passages=retrieval_result.get("final_top_k"),
245
- max_source_items=retrieval_result.get("final_top_k"),
246
- response_mode=response_mode or retrieval_result.get("mode"),
247
- query_profile=retrieval_result.get("query_profile") or {},
248
- retrieval_result=retrieval_result,
249
  )
 
1
  from __future__ import annotations
2
 
3
+ import re
4
  from collections import OrderedDict
5
  from typing import Any, Dict, List
6
 
 
13
  BASE_SYSTEM_PROMPT = """
14
  Bạn là trợ lý trả lời pháp luật Việt Nam.
15
 
16
+ Nguyên tắc bắt buộc:
17
+ - Chỉ dùng ngữ cảnh đã truy xuất để trả lời.
18
+ - Không bịa thêm thông tin không có trong ngữ cảnh.
19
+ - Nội dung ngữ cảnh có gì thì trả lời đúng theo đó.
20
+ - Không suy diễn vượt quá ngữ cảnh truy xuất.
21
+ - Nếu ngữ cảnh chưa đủ để khẳng định thì phải nói rõ là chưa đủ căn cứ.
22
+ - Khi có thể, nêu căn cứ theo văn bản, điều, khoản, điểm hoặc vị trí tương ứng.
23
  """.strip()
24
 
25
+ DOC_SCOPE_SUMMARY_TRIGGERS = [
26
+ "quy định về vấn đề gì",
27
+ "quy định về gì",
28
+ "nói về vấn đề gì",
29
+ "nói về gì",
30
+ "điều chỉnh vấn đề gì",
31
+ "điều chỉnh gì",
32
+ "về vấn đề gì",
33
+ "phạm vi điều chỉnh là gì",
34
+ ]
35
 
36
 
37
  def _norm_space(text: str) -> str:
38
  return " ".join((text or "").split()).strip()
39
 
40
 
41
+ def _clean_preserve_lines(text: str) -> str:
42
+ if text is None:
43
+ return ""
44
+ lines = []
45
+ for raw in str(text).splitlines():
46
+ line = re.sub(r"\s+", " ", raw).strip()
47
+ if line:
48
+ lines.append(line)
49
+ return "\n".join(lines).strip()
50
+
51
+
52
+ def _restore_inline_numbered_list(text: str) -> str:
53
+ raw = _clean_preserve_lines(text)
54
+ if not raw:
55
+ return ""
56
+ restored = re.sub(r"\s+(\d+\.)\s+", r"\n\1 ", raw)
57
+ restored = re.sub(r"\s+([a-zđ]\))\s+", r"\n\1 ", restored, flags=re.IGNORECASE)
58
+ return restored.strip()
59
+
60
+
61
+ def _postprocess_answer(text: str) -> str:
62
+ raw = _clean_preserve_lines(text)
63
+ if not raw:
64
+ return ""
65
+ raw = _restore_inline_numbered_list(raw)
66
+ return raw.strip()
67
+
68
+
69
+ def _is_doc_scope_summary_question(question: str) -> bool:
70
+ q = _norm_space(question).lower()
71
+ if not q:
72
+ return False
73
+ if not any(t in q for t in DOC_SCOPE_SUMMARY_TRIGGERS):
74
+ return False
75
+ return any(x in q for x in ["văn bản", "thông tư", "nghị định", "quyết định", "luật", "bộ luật", "nghị quyết"])
76
+
77
+
78
+ def _score_passage_for_doc_scope(item: Dict[str, Any]) -> tuple:
79
+ md = dict(item.get("metadata") or {})
80
+ artifact = str(md.get("artifact_type") or "").lower()
81
+ path_title = _norm_space(str(md.get("path_title") or md.get("title") or "")).lower()
82
+ text = _norm_space(str(item.get("local_text") or item.get("text") or item.get("snippet") or "")).lower()
83
+ final_score = float(item.get("final_score", 0.0) or 0.0)
84
+
85
+ artifact_rank = 0
86
+ if artifact == "doc_sketch":
87
+ artifact_rank = 4
88
+ elif artifact == "article_bundle" and ("điều 1" in path_title or "phạm vi điều chỉnh" in text):
89
+ artifact_rank = 3
90
+ elif artifact == "evidence" and ("điều 1" in path_title or "phạm vi điều chỉnh" in text):
91
+ artifact_rank = 2
92
+ elif "phạm vi điều chỉnh" in text:
93
+ artifact_rank = 1
94
+
95
+ path_rank = 0
96
+ if "điều 1" in path_title:
97
+ path_rank += 2
98
+ if "phạm vi điều chỉnh" in path_title:
99
+ path_rank += 2
100
+
101
+ text_rank = 0
102
+ if "phạm vi điều chỉnh" in text:
103
+ text_rank += 3
104
+ if text.startswith("điều 1."):
105
+ text_rank += 1
106
+
107
+ return (artifact_rank, path_rank, text_rank, final_score)
108
+
109
+
110
+ def _select_passages_for_context(question: str, passages: List[Dict[str, Any]], max_items: int) -> List[Dict[str, Any]]:
111
+ if not passages:
112
+ return []
113
+
114
+ if _is_doc_scope_summary_question(question):
115
+ ranked = sorted(passages, key=_score_passage_for_doc_scope, reverse=True)
116
+ return ranked[: min(2, max_items)]
117
 
118
+ return passages[:max_items]
119
 
120
+
121
+ def _group_for_context(passages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
122
  grouped: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()
123
+
124
+ for p in passages:
125
  md = dict(p.get("metadata") or {})
126
+ doc_key = str(p.get("doc_key") or md.get("doc_id") or md.get("official_title") or "unknown")
127
+
128
  bucket = grouped.setdefault(
129
+ doc_key,
130
  {
 
131
  "doc_title": md.get("official_title") or md.get("law_name") or "unknown",
132
  "doc_type": md.get("doc_type") or md.get("law_type") or "Unknown",
133
  "source": md.get("source") or md.get("issuing_agency") or "LocalFile",
 
135
  "doc_best_score": float(p.get("final_score", 0.0) or 0.0),
136
  },
137
  )
138
+ bucket["doc_best_score"] = max(
139
+ bucket["doc_best_score"],
140
+ float(p.get("final_score", 0.0) or 0.0),
141
+ )
142
  bucket["items"].append(p)
143
 
144
  docs = list(grouped.values())
 
146
  return docs
147
 
148
 
149
+ def _build_context(question: str, passages: List[Dict[str, Any]], max_items: int) -> str:
150
+ selected = _select_passages_for_context(question, passages, max_items=max_items)
151
+ docs = _group_for_context(selected)
152
+ blocks: List[str] = []
 
 
 
 
 
 
 
 
 
153
 
154
+ for doc in docs:
155
+ parts = [
156
+ f"Văn bản: {doc['doc_title']}",
157
+ f"Loại: {doc['doc_type']}",
158
+ f"Nguồn: {doc['source']}",
159
+ ]
160
 
161
+ for idx, item in enumerate(doc["items"], start=1):
 
 
 
 
 
 
 
 
 
 
162
  md = dict(item.get("metadata") or {})
163
+ path_title = _norm_space(str(md.get("path_title") or md.get("title") or ""))
164
+ shared_text = _clean_preserve_lines(str(item.get("shared_text") or ""))
165
+ local_text = _restore_inline_numbered_list(
166
+ str(item.get("local_text") or item.get("text") or item.get("snippet") or "")
167
  )
 
 
 
 
 
168
 
169
+ section_bits: List[str] = [f"[Đoạn {idx}]"]
 
 
 
 
 
 
 
 
 
 
 
170
 
171
+ if path_title:
172
+ section_bits.append(f"Vị trí: {path_title}")
173
+ if shared_text:
174
+ section_bits.append(shared_text)
175
+ if local_text:
176
+ section_bits.append(local_text)
177
 
178
+ parts.append("\n".join(section_bits))
 
 
 
 
 
 
179
 
180
+ blocks.append("\n".join(parts))
181
 
182
+ return "\n\n" + ("\n\n---\n\n".join(blocks) if blocks else "")
 
 
 
 
 
 
 
 
 
 
183
 
184
 
185
+ def _build_sources(question: str, passages: List[Dict[str, Any]], max_items: int) -> List[SourceItem]:
186
+ selected = _select_passages_for_context(question, passages, max_items=max_items)
187
+ out: List[SourceItem] = []
188
+ seen = set()
 
189
 
190
+ for p in selected:
191
+ md = dict(p.get("metadata") or {})
192
+ chunk_id = str(p.get("node_id") or md.get("chunk_id") or md.get("node_id") or "")
193
+ if not chunk_id or chunk_id in seen:
194
+ continue
195
+ seen.add(chunk_id)
196
+
197
+ out.append(
198
+ SourceItem(
199
+ chunk_id=chunk_id,
200
+ law_name=str(md.get("official_title") or md.get("law_name") or "unknown"),
201
+ law_type=str(md.get("doc_type") or md.get("law_type") or "Unknown"),
202
+ year=int(md.get("year") or 0),
203
+ source=str(md.get("source") or md.get("issuing_agency") or "LocalFile"),
204
+ article=str(md.get("article") or "") or None,
205
+ snippet=str(p.get("snippet") or p.get("text") or "")[:700],
206
  )
 
 
 
 
 
 
 
 
 
 
 
207
  )
208
 
209
+ return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
 
 
 
 
211
 
212
+ def _build_user_prompt(question: str, context: str) -> str:
213
+ if _is_doc_scope_summary_question(question):
214
+ extra = """
215
+ Yêu cầu bổ sung cho loại câu hỏi này:
216
+ - Đây là câu hỏi hỏi chủ đề hoặc phạm vi chính của văn bản.
217
+ - Ưu tiên trả lời gọn trong 1 câu nếu ngữ cảnh đã đủ rõ.
218
+ - Chỉ nêu nội dung chính của văn bản.
219
+ - Không mở rộng sang các điều khoản chi tiết khác nếu câu hỏi không yêu cầu.
220
+ """.strip()
221
+ else:
222
+ extra = """
223
+ Yêu cầu bổ sung:
224
+ - Trả lời dựa hoàn toàn trên ngữ cảnh truy xuất.
225
+ - Không thêm thông tin ngoài ngữ cảnh.
226
+ - Không cần cố rút gọn.
227
+ - Không cần ép buộc theo mẫu liệt kê hay trả lời ngắn.
228
+ - Trình bày tự nhiên, miễn là bám sát ngữ cảnh.
229
+ - Nếu ngữ cảnh chỉ nói được đến đâu thì trả lời đúng đến đó.
230
+ """.strip()
231
 
232
+ return f"""
233
+ Câu hỏi:
234
  {question}
235
 
236
+ Ngữ cảnh:
 
 
 
237
  {context}
238
 
239
+ {extra}
240
+
241
+ Nếu có thể, nêu căn cứ theo văn bản và vị trí tương ứng.
 
 
 
242
  """.strip()
243
 
244
+
245
+ def answer_with_rag(question: str, retrieval_result: Dict[str, Any]) -> ChatResponse:
246
+ passages = list(retrieval_result.get("passages") or [])
247
+ insufficient = bool(retrieval_result.get("insufficient_context"))
248
+
249
+ if insufficient or not passages:
250
+ return ChatResponse(
251
+ answer="Ngữ cảnh truy xuất hiện tại chưa đủ căn cứ để trả lời chính xác câu hỏi này.",
252
+ sources=[],
253
+ )
254
+
255
+ context = _build_context(question, passages, max_items=settings.answer_max_context_passages)
256
+ user_prompt = _build_user_prompt(question, context)
257
+
258
  llm = get_llm()
259
+ resp = llm.invoke(
260
+ [
261
+ SystemMessage(content=BASE_SYSTEM_PROMPT),
262
+ HumanMessage(content=user_prompt),
263
+ ]
264
+ )
265
+
266
+ answer = _postprocess_answer(getattr(resp, "content", "") or "")
267
  if not answer:
268
+ answer = "Chưa đủ căn cứ để trả lời chính xác từ ngữ cảnh hiện có."
269
 
270
+ return ChatResponse(
271
+ answer=answer,
272
+ sources=_build_sources(question, passages, max_items=settings.answer_max_source_items),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  )
src/rag/rerank_cross.py CHANGED
@@ -2,14 +2,13 @@ from __future__ import annotations
2
 
3
  import logging
4
  import re
5
- from typing import Any, Dict, List, Optional
6
 
7
  from sentence_transformers import CrossEncoder
8
 
9
  from src.app.settings import settings
10
 
11
  logger = logging.getLogger(__name__)
12
-
13
  _ce: CrossEncoder | None = None
14
 
15
 
@@ -28,97 +27,50 @@ def _norm_space(text: str) -> str:
28
  return " ".join((text or "").split()).strip()
29
 
30
 
31
- def _normalize_rerank_text(text: str, *, max_chars: int = 1800) -> str:
32
  clean = _norm_space(str(text or ""))
33
- clean = re.sub(r"\[(DOC_TYPE|OFFICIAL_TITLE|ISSUING_AGENCY|LEAD_BLOCK|PATH|NODE_TYPE|CHUNK)\]\s*", " ", clean)
 
 
 
 
34
  clean = re.sub(r"\s+", " ", clean).strip()
35
  if len(clean) <= max_chars:
36
  return clean
37
  return clean[: max(0, max_chars - 3)].rstrip() + "..."
38
 
39
 
40
- def _build_rerank_text(passage: Dict[str, Any]) -> str:
41
  raw = str(
42
- passage.get("rerank_text_short")
43
- or passage.get("rerank_text")
44
- or passage.get("retrieval_text")
45
- or passage.get("text")
46
- or passage.get("snippet")
47
  or ""
48
  )
49
  return _normalize_rerank_text(raw)
50
 
51
 
52
- def _intent_adjustment(question: str, passage: Dict[str, Any], query_profile: Optional[Dict[str, Any]]) -> float:
53
- profile = query_profile or {}
54
- route = str(profile.get("route") or "")
55
- heading_text = _norm_space(str(passage.get("heading_text") or (passage.get("metadata") or {}).get("path_title") or "")).lower()
56
- artifact_type = str((passage.get("metadata") or {}).get("artifact_type") or "")
57
-
58
- boost = 0.0
59
- primary_heading_term = str(profile.get("primary_heading_term") or "").strip().lower()
60
- conflicting = [str(x).lower() for x in (profile.get("conflicting_heading_terms") or [])]
61
-
62
- if route == "heading_list":
63
- if artifact_type == "article_bundle":
64
- boost += 0.12
65
- if primary_heading_term and primary_heading_term in heading_text:
66
- boost += 0.18
67
- if conflicting and any(term in heading_text for term in conflicting) and primary_heading_term not in heading_text:
68
- boost -= 0.20
69
-
70
- if route == "version_change":
71
- q = question.lower()
72
- if any(term in q for term in ["bãi bỏ", "hết hiệu lực"]) and any(term in heading_text for term in ["bãi bỏ", "hết hiệu lực"]):
73
- boost += 0.18
74
- if any(term in q for term in ["sửa đổi", "bổ sung", "thay thế"]) and any(term in heading_text for term in ["sửa đổi", "bổ sung", "thay thế"]):
75
- boost += 0.14
76
-
77
- return boost
78
-
79
-
80
- def cross_rerank(
81
- question: str,
82
- passages: List[Dict[str, Any]],
83
- top_n: int,
84
- *,
85
- query_profile: Optional[Dict[str, Any]] = None,
86
- ) -> List[Dict[str, Any]]:
87
  if not passages:
88
  return []
89
 
90
- top_n = max(0, min(int(top_n or 0), len(passages)))
91
- if top_n == 0:
92
- return []
93
 
94
- try:
95
- ce = get_cross_encoder()
96
- pairs = [[question, _build_rerank_text(p)] for p in passages]
97
- scores = ce.predict(pairs)
98
- except Exception as exc:
99
- logger.warning("Cross rerank failed, fallback to input order: %s", exc)
100
- out: List[Dict[str, Any]] = []
101
- for p in passages[:top_n]:
102
- item = dict(p)
103
- item.setdefault("cross_score", 0.0)
104
- out.append(item)
105
- return out
106
-
107
- scored: List[Dict[str, Any]] = []
108
- for score, passage in zip(scores, passages):
109
- item = dict(passage)
110
- base = float(score)
111
- adjust = _intent_adjustment(question, passage, query_profile)
112
- item["cross_score_raw"] = base
113
- item["cross_score"] = base + adjust
114
- scored.append(item)
115
-
116
- scored.sort(
117
- key=lambda x: (
118
- float(x.get("cross_score", 0.0)),
119
- float(x.get("hybrid_score", 0.0)),
120
- float(x.get("doc_score", 0.0)),
121
- ),
122
- reverse=True,
123
- )
124
- return scored[:top_n]
 
2
 
3
  import logging
4
  import re
5
+ from typing import Any, Dict, List
6
 
7
  from sentence_transformers import CrossEncoder
8
 
9
  from src.app.settings import settings
10
 
11
  logger = logging.getLogger(__name__)
 
12
  _ce: CrossEncoder | None = None
13
 
14
 
 
27
  return " ".join((text or "").split()).strip()
28
 
29
 
30
+ def _normalize_rerank_text(text: str, *, max_chars: int = 1500) -> str:
31
  clean = _norm_space(str(text or ""))
32
+ clean = re.sub(
33
+ r"\[(DOC_TYPE|OFFICIAL_TITLE|ISSUING_AGENCY|LEAD_BLOCK|PATH|NODE_TYPE|CHUNK)\]\s*",
34
+ " ",
35
+ clean,
36
+ )
37
  clean = re.sub(r"\s+", " ", clean).strip()
38
  if len(clean) <= max_chars:
39
  return clean
40
  return clean[: max(0, max_chars - 3)].rstrip() + "..."
41
 
42
 
43
+ def build_anchor_rerank_text(candidate: Dict[str, Any]) -> str:
44
  raw = str(
45
+ candidate.get("rerank_text_short")
46
+ or candidate.get("rerank_text")
47
+ or candidate.get("retrieval_text")
48
+ or candidate.get("text")
49
+ or candidate.get("snippet")
50
  or ""
51
  )
52
  return _normalize_rerank_text(raw)
53
 
54
 
55
+ def cross_rerank(question: str, passages: List[Dict[str, Any]], top_n: int) -> List[Dict[str, Any]]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  if not passages:
57
  return []
58
 
59
+ question = _norm_space(question)
60
+ ce = get_cross_encoder()
 
61
 
62
+ pairs = []
63
+ for p in passages:
64
+ rerank_text = build_anchor_rerank_text(p)
65
+ pairs.append((question, rerank_text))
66
+
67
+ scores = ce.predict(pairs)
68
+
69
+ rescored: List[Dict[str, Any]] = []
70
+ for p, score in zip(passages, scores):
71
+ item = dict(p)
72
+ item["cross_score"] = float(score)
73
+ rescored.append(item)
74
+
75
+ rescored.sort(key=lambda x: float(x.get("cross_score", 0.0)), reverse=True)
76
+ return rescored[: max(1, int(top_n or 1))]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/rag/retrieval_pipeline.py CHANGED
@@ -4,28 +4,61 @@ import hashlib
4
  import logging
5
  import math
6
  import re
7
- from collections import defaultdict
8
- from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
9
-
10
- from src.rag.auto_filter import infer_filters, infer_query_profile
11
- from src.rag.hybrid import bm25_score, tokenize
 
 
 
 
 
12
  from src.rag.openai_clients import get_embedings
13
  from src.rag.rerank_cross import cross_rerank
14
 
15
  logger = logging.getLogger(__name__)
16
 
17
- _DOCUMENT_TOP_K = 3
18
- _PASSAGES_PER_DOC = 8
19
- _FINAL_TOP_K = 8
20
-
21
  _DOC_EMBED_CACHE: Dict[str, List[float]] = {}
22
- _PASSAGE_EMBED_CACHE: Dict[str, List[float]] = {}
23
  _QUESTION_EMBED_CACHE: Dict[str, List[float]] = {}
24
 
25
 
26
  # =========================
27
  # Basic helpers
28
  # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  def _norm_space(text: str) -> str:
31
  return " ".join((text or "").split()).strip()
@@ -35,13 +68,35 @@ def _text_cache_key(text: str) -> str:
35
  return hashlib.sha1(_norm_space(text).encode("utf-8")).hexdigest()
36
 
37
 
38
- def _graph_runtime_cache(graph: Dict[str, Any]) -> Dict[str, Any]:
39
- cache = graph.get("__retrieval_runtime_cache__")
40
- if isinstance(cache, dict):
41
- return cache
42
- cache = {}
43
- graph["__retrieval_runtime_cache__"] = cache
44
- return cache
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
47
  def _cosine(a: List[float], b: List[float]) -> float:
@@ -71,922 +126,1085 @@ def _minmax(values: List[float]) -> List[float]:
71
  return [(v - lo) / (hi - lo) for v in values]
72
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  def _node_index(graph: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
75
  idx = graph.get("node_index", {}) or {}
76
  if idx:
77
  return idx
78
- runtime_cache = _graph_runtime_cache(graph)
79
- cached = runtime_cache.get("node_index") or {}
80
- if cached:
81
- return cached
82
  out: Dict[str, Dict[str, Any]] = {}
83
- for node in graph.get("nodes", []) or []:
84
  node_id = str(node.get("node_id") or "").strip()
85
  if node_id:
86
  out[node_id] = node
87
- runtime_cache["node_index"] = out
88
  return out
89
 
90
 
91
- def _artifact_type(node: Dict[str, Any]) -> str:
92
- return str((node.get("metadata", {}) or {}).get("artifact_type") or "evidence").strip().lower()
93
 
94
 
95
  def _node_type(node: Dict[str, Any]) -> str:
96
- return str(node.get("node_type") or (node.get("metadata", {}) or {}).get("node_type") or "").strip().lower()
97
 
98
 
99
- def _candidate_doc_key(metadata: Dict[str, Any]) -> str:
100
- for key in ["doc_id", "law_name", "official_title", "document_title", "file_stem"]:
101
- value = str(metadata.get(key) or "").strip().lower()
102
- if value:
103
- return value
104
- return "unknown"
105
 
106
 
107
- def _path_label(md: Dict[str, Any]) -> str:
108
- for key in ["path_title", "title", "heading_title", "article", "clause", "point"]:
109
- value = md.get(key)
110
- if value is not None and str(value).strip():
111
- return str(value).strip()
112
- return "-"
113
 
114
 
115
- def _first_sentences(text: str, *, max_sentences: int = 2, max_chars: int = 420) -> str:
116
- clean = _norm_space(text)
117
- if not clean:
118
- return ""
119
- parts = [part.strip() for part in re.split(r"(?<=[.!?])\s+", clean) if part and part.strip()]
120
- if not parts:
121
- return clean[:max_chars]
122
- merged = " ".join(parts[: max(1, int(max_sentences))]).strip()
123
- if len(merged) <= max_chars:
124
- return merged
125
- return merged[: max(0, max_chars - 3)].rstrip() + "..."
126
 
127
 
128
- def _short(text: str, *, limit: int = 260) -> str:
129
  clean = _norm_space(text)
130
  if len(clean) <= limit:
131
  return clean
132
  return clean[: max(0, limit - 3)].rstrip() + "..."
133
 
134
 
135
- def _batch_embed_texts(texts: List[str], *, cache: Dict[str, List[float]]) -> Dict[str, List[float]]:
136
- out: Dict[str, List[float]] = {}
137
- misses: List[Tuple[str, str]] = []
138
- for text in texts:
139
- key = _text_cache_key(text)
140
- if key in cache:
141
- out[key] = cache[key]
142
  else:
143
- misses.append((key, text))
144
-
145
- if misses:
146
- embeddings = get_embedings()
147
- vectors = embeddings.embed_documents([text for _, text in misses])
148
- for (key, _), vec in zip(misses, vectors):
149
- cache[key] = list(vec)
150
- out[key] = cache[key]
151
  return out
152
 
153
 
154
- def _question_embedding(question: str) -> List[float]:
155
- q = _norm_space(question)
156
- key = _text_cache_key(q)
157
- cached = _QUESTION_EMBED_CACHE.get(key)
158
- if cached is not None:
159
- return cached
160
- embeddings = get_embedings()
161
- vec = list(embeddings.embed_query(q))
162
- _QUESTION_EMBED_CACHE[key] = vec
163
- return vec
164
-
165
-
166
- def _bm25_value(question: str, text: str) -> float:
167
- return bm25_score(tokenize(question), tokenize(text))
168
-
169
-
170
- def _sorted_ids_by_score(items: List[Dict[str, Any]], score_key: str) -> List[str]:
171
- ranked = sorted(items, key=lambda x: float(x.get(score_key, 0.0) or 0.0), reverse=True)
172
- return [str(item.get("id") or "") for item in ranked if str(item.get("id") or "")]
173
-
174
-
175
- def _rrf_fuse(rank_lists: List[List[str]], *, k: int = 60) -> Dict[str, float]:
176
- scores: Dict[str, float] = defaultdict(float)
177
- for ranked in rank_lists:
178
- for rank, item_id in enumerate(ranked, start=1):
179
- if not item_id:
180
- continue
181
- scores[item_id] += 1.0 / (k + rank)
182
- return dict(scores)
183
-
184
-
185
  # =========================
186
- # Graph catalog
187
  # =========================
188
 
189
- def _sorted_node_ids(node_ids: Iterable[str], node_idx: Dict[str, Dict[str, Any]]) -> List[str]:
190
- return sorted(
191
- {str(nid) for nid in node_ids if str(nid)},
192
- key=lambda nid: int((node_idx.get(nid, {}).get("metadata", {}) or {}).get("order_index") or 0),
193
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
 
196
  def _build_doc_catalog(graph: Dict[str, Any]) -> List[Dict[str, Any]]:
197
- runtime_cache = _graph_runtime_cache(graph)
198
- cached = runtime_cache.get("doc_catalog")
199
- if isinstance(cached, list) and cached:
200
- return cached
201
-
202
  node_idx = _node_index(graph)
 
 
203
  buckets: Dict[str, Dict[str, Any]] = {}
204
 
205
  for node_id, node in node_idx.items():
206
- md = dict(node.get("metadata") or {})
207
- doc_key = _candidate_doc_key(md)
208
- if doc_key == "unknown":
209
  continue
 
210
  bucket = buckets.setdefault(
211
- doc_key,
212
  {
213
- "id": doc_key,
214
- "doc_key": doc_key,
215
- "doc_id": md.get("doc_id") or doc_key,
216
- "law_name": md.get("official_title") or md.get("law_name") or doc_key,
217
- "official_title": md.get("official_title") or md.get("law_name") or doc_key,
218
- "law_type": md.get("doc_type") or md.get("law_type") or "Unknown",
219
- "doc_type": md.get("doc_type") or md.get("law_type") or "Unknown",
220
- "source": md.get("source") or md.get("issuing_agency") or "LocalFile",
221
- "year": int(md.get("year") or 0),
222
- "doc_number": md.get("doc_number") or "",
223
- "title_block": md.get("title_block") or "",
224
- "lead_block": md.get("lead_block") or "",
225
- "doc_sketch": "",
226
- "doc_sketch_node_id": None,
227
- "doc_sketch_source_node_ids": [],
228
- "article_bundle_ids": [],
229
- "evidence_ids": [],
230
- "summary_ids": [],
231
- "article_to_bundle_id": {},
232
- "article_to_evidence_ids": defaultdict(list),
233
- "member_node_ids": set(),
234
  },
235
  )
236
- bucket["member_node_ids"].add(node_id)
237
- if not bucket.get("doc_number") and md.get("doc_number"):
238
- bucket["doc_number"] = md.get("doc_number")
239
- if not bucket.get("law_name") and (md.get("official_title") or md.get("law_name")):
240
- bucket["law_name"] = md.get("official_title") or md.get("law_name")
241
- if not bucket.get("official_title") and (md.get("official_title") or md.get("law_name")):
242
- bucket["official_title"] = md.get("official_title") or md.get("law_name")
243
- if bucket.get("law_type") in (None, "", "Unknown") and (md.get("doc_type") or md.get("law_type")):
244
- bucket["law_type"] = md.get("doc_type") or md.get("law_type")
245
- if bucket.get("doc_type") in (None, "", "Unknown") and (md.get("doc_type") or md.get("law_type")):
246
- bucket["doc_type"] = md.get("doc_type") or md.get("law_type")
247
- if not bucket.get("title_block") and md.get("title_block"):
248
- bucket["title_block"] = md.get("title_block")
249
- if not bucket.get("lead_block") and md.get("lead_block"):
250
- bucket["lead_block"] = md.get("lead_block")
251
- if not bucket.get("source") and (md.get("source") or md.get("issuing_agency")):
252
- bucket["source"] = md.get("source") or md.get("issuing_agency")
253
- if not bucket.get("year") and md.get("year"):
254
- bucket["year"] = int(md.get("year") or 0)
255
-
256
- artifact = _artifact_type(node)
257
- if artifact == "doc_sketch":
258
- bucket["doc_sketch"] = _norm_space(str(node.get("text") or ""))
259
  bucket["doc_sketch_node_id"] = node_id
260
- bucket["doc_sketch_source_node_ids"] = list(md.get("source_node_ids") or [])
261
- elif artifact == "article_bundle":
262
- bucket["article_bundle_ids"].append(node_id)
263
- article = str(md.get("article") or "").strip()
264
- if article and article not in bucket["article_to_bundle_id"]:
265
- bucket["article_to_bundle_id"][article] = node_id
266
- elif artifact == "evidence":
267
- bucket["evidence_ids"].append(node_id)
268
- article = str(md.get("article") or "").strip()
269
- if article:
270
- bucket["article_to_evidence_ids"][article].append(node_id)
271
- elif artifact == "summary":
272
- bucket["summary_ids"].append(node_id)
273
 
274
- out: List[Dict[str, Any]] = []
275
- for bucket in buckets.values():
276
- bucket["article_bundle_ids"] = _sorted_node_ids(bucket["article_bundle_ids"], node_idx)
277
- bucket["evidence_ids"] = _sorted_node_ids(bucket["evidence_ids"], node_idx)
278
- bucket["summary_ids"] = _sorted_node_ids(bucket["summary_ids"], node_idx)
279
- bucket["member_node_ids"] = sorted(bucket["member_node_ids"])
280
- bucket["article_to_evidence_ids"] = {
281
- art: _sorted_node_ids(ids, node_idx) for art, ids in bucket["article_to_evidence_ids"].items()
282
- }
283
- if not bucket["doc_sketch"]:
284
- article_titles = []
285
- for bundle_id in bucket["article_bundle_ids"][:15]:
286
- md = dict((node_idx.get(bundle_id) or {}).get("metadata") or {})
287
- title = _path_label(md)
288
- if title:
289
- article_titles.append(title)
290
- parts = []
291
- if bucket["law_type"]:
292
- parts.append(f"Loại văn bản: {bucket['law_type']}")
293
- if bucket["law_name"]:
294
- parts.append(f"Tiêu đề: {bucket['law_name']}")
295
- if bucket["doc_number"]:
296
- parts.append(f"Số văn bản: {bucket['doc_number']}")
297
- if article_titles:
298
- parts.append("Các điều chính:\n" + "\n".join(f"- {x}" for x in article_titles))
299
- bucket["doc_sketch"] = "\n".join(parts).strip()
300
- out.append(bucket)
301
-
302
- out.sort(key=lambda x: str(x.get("law_name") or x.get("doc_key") or ""))
303
- runtime_cache["doc_catalog"] = out
304
- return out
305
 
 
 
 
 
 
306
 
307
- DOC_NUMBER_ANY_RE = re.compile(r"\b0*(\d{1,4})\s*/\s*(\d{4})\s*/\s*([A-ZĐ\-][A-ZĐ\-\s]*)\b", re.IGNORECASE)
308
 
 
 
309
 
310
- def _extract_doc_number(text: str) -> str:
311
- s = _norm_space(str(text or ""))
312
- if not s:
313
- return ""
314
- m = DOC_NUMBER_ANY_RE.search(s.upper())
315
- if not m:
316
- return ""
317
- first = str(int(m.group(1)))
318
- year = m.group(2)
319
- tail = re.sub(r"\s+", "", m.group(3).upper())
320
- return f"{first}/{year}/{tail}"
321
 
 
 
322
 
323
- def _normalize_doc_number(text: str) -> str:
324
- s = _norm_space(str(text or "")).upper()
325
- if not s:
326
- return ""
327
- extracted = _extract_doc_number(s)
328
- if extracted:
329
- return extracted
330
- return re.sub(r"\s+", "", s)
331
 
 
 
 
 
 
332
 
333
- def _normalize_law_type(text: str) -> str:
334
- raw = _norm_space(str(text or "")).lower()
335
- if not raw:
336
- return ""
337
- aliases = {
338
- "thông tư": "thông tư",
339
- "thong tu": "thông tư",
340
- "tt": "thông tư",
341
- "nghị định": "nghị định",
342
- "nghi dinh": "nghị định",
343
- "nd": "nghị định",
344
- "quyết định": "quyết định",
345
- "quyet dinh": "quyết định",
346
- "qd": "quyết định",
347
- "luật": "luật",
348
- "bo luat": "bộ luật",
349
- "bộ luật": "bộ luật",
350
- "nghị quyết": "nghị quyết",
351
- "nghi quyet": "nghị quyết",
352
- }
353
- return aliases.get(raw, raw)
 
354
 
 
 
355
 
356
- def _infer_year_from_doc_number(text: str) -> int:
357
- norm = _normalize_doc_number(text) or _extract_doc_number(text)
358
- m = re.search(r"/(\d{4})/", norm)
359
- return int(m.group(1)) if m else 0
360
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
- def _doc_filter_text(doc_or_md: Dict[str, Any]) -> str:
363
- parts = [
364
- str(doc_or_md.get("doc_number") or ""),
365
- str(doc_or_md.get("law_name") or ""),
366
- str(doc_or_md.get("official_title") or ""),
367
- str(doc_or_md.get("doc_sketch") or ""),
368
- str(doc_or_md.get("title_block") or ""),
369
- str(doc_or_md.get("lead_block") or ""),
370
- str(doc_or_md.get("law_type") or doc_or_md.get("doc_type") or ""),
371
- ]
372
- return _norm_space("\n".join(x for x in parts if _norm_space(x))).lower()
373
-
374
-
375
- def _compact(text: str) -> str:
376
- return re.sub(r"\s+", "", str(text or "")).upper()
377
-
378
-
379
- def _matches_filters(doc_or_md: Dict[str, Any], filters: Dict[str, Any], *, relaxed: bool = False) -> bool:
380
- if not filters:
381
- return True
382
-
383
- haystack = _doc_filter_text(doc_or_md)
384
- haystack_compact = _compact(haystack)
385
-
386
- want_doc_number = _normalize_doc_number(filters.get("doc_number") or "")
387
- if want_doc_number:
388
- have_doc_number = _normalize_doc_number(doc_or_md.get("doc_number") or doc_or_md.get("doc_number".lower()) or "")
389
- if not have_doc_number:
390
- have_doc_number = _extract_doc_number(haystack)
391
- if have_doc_number:
392
- if relaxed:
393
- if want_doc_number != have_doc_number and want_doc_number not in have_doc_number and have_doc_number not in want_doc_number:
394
- return False
395
- elif want_doc_number != have_doc_number:
396
- return False
397
- elif want_doc_number not in haystack_compact:
398
- return False
399
-
400
- want_law_type = _normalize_law_type(filters.get("law_type") or "")
401
- if want_law_type:
402
- have_law_type = _normalize_law_type(doc_or_md.get("law_type") or doc_or_md.get("law_type".lower()) or doc_or_md.get("doc_type") or "")
403
- if have_law_type:
404
- if not relaxed and want_law_type != have_law_type:
405
- return False
406
- if relaxed and want_law_type != have_law_type and want_law_type not in haystack:
407
- return False
408
- elif want_law_type not in haystack:
409
- return False
410
-
411
- want_year = int(filters.get("year") or 0)
412
- if want_year:
413
- have_year = int(doc_or_md.get("year") or 0)
414
- if not have_year:
415
- have_year = _infer_year_from_doc_number(doc_or_md.get("doc_number") or haystack)
416
- if have_year and have_year != want_year:
417
- return False
418
-
419
- return True
420
-
421
-
422
- def _doc_boost(doc: Dict[str, Any], query_profile: Dict[str, Any]) -> float:
423
- boost = 0.0
424
- filters = query_profile.get("filters") or {}
425
- doc_number = _normalize_doc_number(filters.get("doc_number") or "")
426
- have_doc_number = _normalize_doc_number(doc.get("doc_number") or "") or _extract_doc_number(_doc_filter_text(doc))
427
- if doc_number and have_doc_number and doc_number == have_doc_number:
428
- boost += 0.38
429
- law_type = _normalize_law_type(filters.get("law_type") or "")
430
- have_law_type = _normalize_law_type(doc.get("law_type") or doc.get("doc_type") or "")
431
- if law_type and have_law_type and law_type == have_law_type:
432
- boost += 0.08
433
- want_year = int(filters.get("year") or 0)
434
- have_year = int(doc.get("year") or 0) or _infer_year_from_doc_number(doc.get("doc_number") or "")
435
- if want_year and have_year and want_year == have_year:
436
- boost += 0.04
437
- return boost
438
-
439
-
440
- def _filter_docs_relaxed(docs: List[Dict[str, Any]], filters: Dict[str, Any]) -> List[Dict[str, Any]]:
441
- if not filters:
442
- return docs
443
- return [doc for doc in docs if _matches_filters(doc, filters, relaxed=True)]
444
-
445
-
446
- def _doc_rank_fields(doc: Dict[str, Any]) -> Dict[str, str]:
447
- title = _norm_space(str(doc.get("official_title") or doc.get("law_name") or ""))
448
- sketch = _norm_space(str(doc.get("doc_sketch") or ""))
449
- doc_number = _norm_space(str(doc.get("doc_number") or ""))
450
- title_block = _norm_space(str(doc.get("title_block") or ""))
451
- lead_block = _first_sentences(str(doc.get("lead_block") or ""), max_sentences=3, max_chars=420)
452
- header = _norm_space("\n".join(x for x in [title_block, lead_block] if x))
453
- combined = _norm_space("\n".join(x for x in [doc_number, title, sketch, header] if x))
454
  return {
455
- "doc_number": doc_number,
456
- "title": title,
457
- "sketch": sketch,
458
- "header": header,
459
- "combined": combined,
460
  }
461
 
462
 
463
- def _prefilter_docs_for_rescue(question: str, docs: List[Dict[str, Any]], filters: Dict[str, Any], *, limit: int = 64) -> List[Dict[str, Any]]:
464
- if not docs:
465
- return []
466
- want_doc_number = _normalize_doc_number(filters.get("doc_number") or "")
467
- want_law_type = _normalize_law_type(filters.get("law_type") or "")
468
- want_year = int(filters.get("year") or 0)
469
- scored: List[Tuple[float, Dict[str, Any]]] = []
470
- for doc in docs:
471
- fields = _doc_rank_fields(doc)
472
- score = 0.0
473
- combined = fields["combined"]
474
- title = fields["title"]
475
- sketch = fields["sketch"]
476
- score += 1.25 * _bm25_value(question, title)
477
- score += 1.00 * _bm25_value(question, sketch)
478
- score += 0.75 * _bm25_value(question, combined)
479
- have_doc_number = _normalize_doc_number(fields["doc_number"]) or _extract_doc_number(combined)
480
- if want_doc_number and have_doc_number == want_doc_number:
481
- score += 10.0
482
- elif want_doc_number and want_doc_number and want_doc_number in _compact(combined):
483
- score += 6.0
484
- have_law_type = _normalize_law_type(doc.get("law_type") or doc.get("doc_type") or "")
485
- if want_law_type and have_law_type == want_law_type:
486
- score += 1.5
487
- have_year = int(doc.get("year") or 0) or _infer_year_from_doc_number(fields["doc_number"])
488
- if want_year and have_year == want_year:
489
- score += 1.0
490
- if score > 0:
491
- scored.append((score, doc))
492
- scored.sort(key=lambda x: (x[0], len(str(x[1].get("doc_sketch") or ""))), reverse=True)
493
- return [doc for _, doc in scored[: max(1, int(limit or 1))]]
494
-
495
-
496
- def _rank_documents_multifield_rrf(
497
- question: str,
498
- docs: List[Dict[str, Any]],
499
- *,
500
- top_k: int,
501
- question_vec: Optional[List[float]] = None,
502
- query_profile: Optional[Dict[str, Any]] = None,
503
- seed_stage: str = "strict",
504
- ) -> List[Dict[str, Any]]:
505
- if not docs:
506
- return []
507
 
508
- qv = question_vec or _question_embedding(question)
509
- fields_by_id: Dict[str, Dict[str, str]] = {}
510
- id_to_doc: Dict[str, Dict[str, Any]] = {}
511
- title_texts: List[str] = []
512
- sketch_texts: List[str] = []
513
- combined_texts: List[str] = []
514
  for doc in docs:
515
- doc_id = str(doc.get("id") or "")
516
- fields = _doc_rank_fields(doc)
517
- fields_by_id[doc_id] = fields
518
- id_to_doc[doc_id] = doc
519
- title_texts.append(fields["title"] or fields["combined"])
520
- sketch_texts.append(fields["sketch"] or fields["combined"])
521
- combined_texts.append(fields["combined"] or fields["title"] or fields["sketch"])
522
-
523
- title_embeds = _batch_embed_texts(title_texts, cache=_DOC_EMBED_CACHE)
524
- sketch_embeds = _batch_embed_texts(sketch_texts, cache=_DOC_EMBED_CACHE)
525
- combined_embeds = _batch_embed_texts(combined_texts, cache=_DOC_EMBED_CACHE)
526
-
527
- rank_lists: List[List[str]] = []
528
- scored_lists: List[Tuple[str, List[Dict[str, Any]]]] = []
529
- bm25_docno_items: List[Dict[str, Any]] = []
530
- bm25_title_items: List[Dict[str, Any]] = []
531
- bm25_sketch_items: List[Dict[str, Any]] = []
532
- bm25_header_items: List[Dict[str, Any]] = []
533
- dense_title_items: List[Dict[str, Any]] = []
534
- dense_sketch_items: List[Dict[str, Any]] = []
535
- dense_combined_items: List[Dict[str, Any]] = []
536
-
537
- for doc_id, doc in id_to_doc.items():
538
- fields = fields_by_id[doc_id]
539
- boost = _doc_boost(doc, query_profile or {})
540
- docno_text = fields["doc_number"] or fields["combined"]
541
- title_text = fields["title"] or fields["combined"]
542
- sketch_text = fields["sketch"] or fields["combined"]
543
- header_text = fields["header"] or fields["combined"]
544
- combined_text = fields["combined"] or title_text or sketch_text or header_text
545
-
546
- bm25_docno_items.append({"id": doc_id, "score": _bm25_value(question, docno_text) + 1.2 * boost})
547
- bm25_title_items.append({"id": doc_id, "score": _bm25_value(question, title_text) + 0.8 * boost})
548
- bm25_sketch_items.append({"id": doc_id, "score": _bm25_value(question, sketch_text) + 0.7 * boost})
549
- bm25_header_items.append({"id": doc_id, "score": _bm25_value(question, header_text) + 0.5 * boost})
550
-
551
- dense_title = _cosine(qv, title_embeds.get(_text_cache_key(title_text), []))
552
- dense_sketch = _cosine(qv, sketch_embeds.get(_text_cache_key(sketch_text), []))
553
- dense_combined = _cosine(qv, combined_embeds.get(_text_cache_key(combined_text), []))
554
- dense_title_items.append({"id": doc_id, "score": dense_title + 0.9 * boost})
555
- dense_sketch_items.append({"id": doc_id, "score": dense_sketch + 0.7 * boost})
556
- dense_combined_items.append({"id": doc_id, "score": dense_combined + 1.0 * boost})
557
-
558
- for items in [bm25_docno_items, bm25_title_items, bm25_sketch_items, bm25_header_items, dense_title_items, dense_sketch_items, dense_combined_items]:
559
- rank_lists.append(_sorted_ids_by_score(items, "score"))
560
-
561
- fused = _rrf_fuse(rank_lists)
562
-
563
- ranked: List[Dict[str, Any]] = []
564
- for doc_id, doc in id_to_doc.items():
565
- fields = fields_by_id[doc_id]
566
- title_text = fields["title"] or fields["combined"]
567
- sketch_text = fields["sketch"] or fields["combined"]
568
- combined_text = fields["combined"] or title_text or sketch_text
569
- dense_title = _cosine(qv, title_embeds.get(_text_cache_key(title_text), []))
570
- dense_sketch = _cosine(qv, sketch_embeds.get(_text_cache_key(sketch_text), []))
571
- dense_combined = _cosine(qv, combined_embeds.get(_text_cache_key(combined_text), []))
572
- bm25_docno = _bm25_value(question, fields["doc_number"] or combined_text)
573
- bm25_title = _bm25_value(question, title_text)
574
- bm25_sketch = _bm25_value(question, sketch_text)
575
- bm25_header = _bm25_value(question, fields["header"] or combined_text)
576
- boost = _doc_boost(doc, query_profile or {})
577
  item = dict(doc)
578
- item["text"] = combined_text
579
- item["dense_score"] = float(max(dense_title, dense_sketch, dense_combined))
580
- item["bm25_score"] = float(max(bm25_docno, bm25_title, bm25_sketch, bm25_header))
581
- item["rrf_score"] = float(fused.get(doc_id, 0.0) + boost)
582
- item["hybrid_score"] = item["rrf_score"]
583
- item["doc_seed_stage"] = seed_stage
584
- item["doc_rank_title"] = fields["title"]
585
- item["doc_rank_header"] = fields["header"]
586
- ranked.append(item)
 
587
 
588
- ranked.sort(key=lambda x: (float(x.get("rrf_score", 0.0)), float(x.get("dense_score", 0.0)), float(x.get("bm25_score", 0.0))), reverse=True)
589
- return ranked[: max(1, int(top_k or _DOCUMENT_TOP_K))]
590
 
 
 
591
 
592
- def rank_documents_by_sketch_rrf(
593
- question: str,
594
- graph: Dict[str, Any],
595
- *,
596
- top_k: int = _DOCUMENT_TOP_K,
597
- question_vec: Optional[List[float]] = None,
598
- filters: Optional[Dict[str, Any]] = None,
599
- query_profile: Optional[Dict[str, Any]] = None,
600
- ) -> List[Dict[str, Any]]:
601
- all_docs = _build_doc_catalog(graph)
602
- active_filters = filters or {}
603
 
604
- strict_docs = [d for d in all_docs if _matches_filters(d, active_filters, relaxed=False)]
605
- if strict_docs:
606
- return _rank_documents_multifield_rrf(
607
- question, strict_docs, top_k=top_k, question_vec=question_vec, query_profile=query_profile, seed_stage="strict"
608
- )
609
 
610
- relaxed_docs = _filter_docs_relaxed(all_docs, active_filters) if active_filters else []
611
- if relaxed_docs:
612
- return _rank_documents_multifield_rrf(
613
- question, relaxed_docs, top_k=top_k, question_vec=question_vec, query_profile=query_profile, seed_stage="relaxed"
614
- )
615
 
616
- rescue_pool = _prefilter_docs_for_rescue(question, all_docs, active_filters, limit=max(32, 8 * max(1, int(top_k or _DOCUMENT_TOP_K))))
617
- if rescue_pool:
618
- return _rank_documents_multifield_rrf(
619
- question, rescue_pool, top_k=top_k, question_vec=question_vec, query_profile=query_profile, seed_stage="rescue_rrf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  )
621
 
622
- return []
 
623
 
624
 
625
- def _field_dense_bm25(question: str, texts: List[str], question_vec: List[float]) -> Tuple[List[float], List[float]]:
626
- embeds = _batch_embed_texts(texts, cache=_PASSAGE_EMBED_CACHE)
627
- dense: List[float] = []
628
- bm25_vals: List[float] = []
629
- for text in texts:
630
- embed = embeds.get(_text_cache_key(text), [])
631
- dense.append(_cosine(question_vec, embed))
632
- bm25_vals.append(_bm25_value(question, text))
633
- return _minmax(dense), _minmax(bm25_vals)
634
 
635
 
636
- def _passage_route_bonus(passage: Dict[str, Any], query_profile: Dict[str, Any]) -> float:
637
- profile = query_profile or {}
 
 
 
 
 
 
 
 
638
  route = str(profile.get("route") or "")
639
- md = dict(passage.get("metadata") or {})
640
- artifact = str(md.get("artifact_type") or "")
641
- heading = _norm_space(str(passage.get("heading_text") or "")).lower()
642
- self_text = _norm_space(str(passage.get("self_retrieval_text") or "")).lower()
643
- boost = 0.0
644
-
645
- if route == "heading_list":
646
- primary = str(profile.get("primary_heading_term") or "").lower()
647
- if artifact == "article_bundle":
648
- boost += 0.18
649
- if primary and primary in heading:
650
- boost += 0.20
651
- conflicting = [str(x).lower() for x in (profile.get("conflicting_heading_terms") or [])]
652
- if conflicting and any(term in heading for term in conflicting) and primary not in heading:
653
- boost -= 0.18
654
-
655
- if route == "version_change":
656
- terms = [str(x).lower() for x in (profile.get("change_terms") or [])]
657
- if any(term in heading or term in self_text for term in terms):
658
- boost += 0.18
659
-
660
- if route == "direct_reference":
661
- filters = profile.get("filters") or {}
662
- if filters.get("article") and _norm_space(str(filters.get("article"))).lower() == _norm_space(str(md.get("article") or "")).lower():
663
- boost += 0.12
664
- if filters.get("clause") and _norm_space(str(filters.get("clause"))).lower() == _norm_space(str(md.get("clause") or "")).lower():
665
- boost += 0.18
666
- if filters.get("point") and _norm_space(str(filters.get("point"))).lower() == _norm_space(str(md.get("point") or "")).lower():
667
- boost += 0.20
668
-
669
- if route == "condition_circumstance":
670
- if any(term in self_text for term in ["trường hợp", "khi", "nếu"]):
671
- boost += 0.06
672
-
673
- return boost
674
-
675
-
676
- def _rank_passages_multifield(
677
- question: str,
678
- passages: List[Dict[str, Any]],
679
- *,
680
- question_vec: Optional[List[float]] = None,
681
- query_profile: Optional[Dict[str, Any]] = None,
682
- ) -> List[Dict[str, Any]]:
683
- if not passages:
684
  return []
685
 
686
- qv = question_vec or _question_embedding(question)
687
- self_texts = [str(p.get("self_retrieval_text") or p.get("text") or "") for p in passages]
688
- heading_texts = [str(p.get("heading_text") or "") for p in passages]
689
- context_texts = [str(p.get("context_text") or "") for p in passages]
690
 
691
- self_dense, self_bm25 = _field_dense_bm25(question, self_texts, qv)
692
- head_dense, head_bm25 = _field_dense_bm25(question, heading_texts, qv)
693
- ctx_dense, ctx_bm25 = _field_dense_bm25(question, context_texts, qv)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
694
 
 
695
  ranked: List[Dict[str, Any]] = []
696
- for idx, item in enumerate(passages):
697
- self_score = 0.60 * self_dense[idx] + 0.40 * self_bm25[idx]
698
- heading_score = 0.45 * head_dense[idx] + 0.55 * head_bm25[idx]
699
- context_score = 0.65 * ctx_dense[idx] + 0.35 * ctx_bm25[idx]
700
- boost = _passage_route_bonus(item, query_profile or {})
701
- enriched = dict(item)
702
- enriched["self_score"] = float(self_score)
703
- enriched["heading_score"] = float(heading_score)
704
- enriched["context_score"] = float(context_score)
705
- enriched["hybrid_score"] = float(0.55 * self_score + 0.30 * heading_score + 0.15 * context_score + boost)
706
- ranked.append(enriched)
707
 
708
  ranked.sort(
709
  key=lambda x: (
710
- float(x.get("hybrid_score", 0.0)),
711
- float(x.get("self_score", 0.0)),
712
- float(x.get("heading_score", 0.0)),
713
- float(x.get("context_score", 0.0)),
714
  ),
715
  reverse=True,
716
  )
717
  return ranked
718
 
719
 
720
- # =========================
721
- # Passage builders
722
- # =========================
723
-
724
- def _article_bundle_title(doc_info: Dict[str, Any], article: str, node_idx: Dict[str, Dict[str, Any]]) -> str:
725
- bundle_id = str((doc_info.get("article_to_bundle_id") or {}).get(article) or "")
726
- if not bundle_id:
727
- return article
728
- md = dict((node_idx.get(bundle_id) or {}).get("metadata") or {})
729
- return _path_label(md) or article
730
 
731
 
732
- def _context_text_for_node(node: Dict[str, Any], doc_info: Dict[str, Any], graph: Dict[str, Any]) -> str:
733
- md = dict(node.get("metadata") or {})
734
- node_idx = _node_index(graph)
735
- parts: List[str] = []
736
-
737
- article = str(md.get("article") or "").strip()
738
- if article:
739
- article_title = _article_bundle_title(doc_info, article, node_idx)
740
- if article_title:
741
- parts.append(f"[Neo cha]\n{article_title}")
742
-
743
- child_ids = [str(x) for x in (md.get("children_ids") or []) if str(x)]
744
- child_titles: List[str] = []
745
- for cid in child_ids[:2]:
746
- child_md = dict((node_idx.get(cid) or {}).get("metadata") or {})
747
- title = _path_label(child_md)
748
- if title:
749
- child_titles.append(title)
750
- if child_titles:
751
- parts.append("[Neo con]\n" + "\n".join(child_titles))
752
- return "\n\n".join(parts).strip()
753
-
754
-
755
- def _build_passage(node: Dict[str, Any], doc_info: Dict[str, Any], graph: Dict[str, Any]) -> Dict[str, Any]:
756
- md = dict(node.get("metadata") or {})
757
- artifact = _artifact_type(node)
758
- doc_title = _norm_space(str(doc_info.get("law_name") or md.get("official_title") or md.get("law_name") or doc_info.get("doc_key") or ""))
759
- self_text = _norm_space(str(node.get("text") or ""))
760
- heading_text = _norm_space("\n".join(x for x in [str(md.get("path_title") or ""), str(md.get("heading_title") or ""), str(md.get("article") or ""), str(md.get("clause") or ""), str(md.get("point") or "")] if _norm_space(x)))
761
- context_text = _context_text_for_node(node, doc_info, graph)
762
- local_blocks = []
763
- if self_text:
764
- label = "Chính node" if artifact != "article_bundle" else "Nội dung điều"
765
- local_blocks.append(f"[{label}]\n{self_text}")
766
- if context_text:
767
- local_blocks.append(context_text)
768
- local_text = "\n\n".join(local_blocks)
769
- shared_text = f"[Văn bản] {doc_title}" if doc_title else ""
770
-
771
- if artifact == "article_bundle":
772
- rerank_label = "Nội dung điều"
773
- elif artifact == "doc_sketch":
774
- rerank_label = "Tóm tắt cấu trúc"
775
- else:
776
- rerank_label = "Chính node"
777
-
778
- rerank_text_short = "\n\n".join(
779
- part for part in [
780
- f"[Văn bản] {doc_title}" if doc_title else "",
781
- f"[Vị trí] {_path_label(md)} | artifact={artifact or _node_type(node) or '-'}",
782
- f"[{rerank_label}]\n{_short(self_text, limit=1500)}" if self_text else "",
783
- context_text and _short(context_text, limit=280),
784
- ] if _norm_space(part)
785
- )
786
 
787
- retrieval_text = "\n\n".join(
788
- part for part in [
789
- f"[Văn bản] {doc_title}" if doc_title else "",
790
- f"[Heading]\n{heading_text}" if heading_text else "",
791
- f"[Nội dung]\n{self_text}" if self_text else "",
792
- context_text,
793
- ] if _norm_space(part)
 
 
794
  )
795
-
796
- return {
797
- "node_id": str(node.get("node_id") or ""),
798
- "text": self_text,
799
- "snippet": _short(self_text, limit=700),
800
- "bundle_text": retrieval_text,
801
- "retrieval_text": retrieval_text,
802
- "rerank_text": rerank_text_short,
803
- "rerank_text_short": rerank_text_short,
804
- "self_retrieval_text": self_text,
805
- "heading_text": heading_text,
806
- "context_text": context_text,
807
- "shared_text": shared_text,
808
- "local_text": local_text,
809
- "metadata": {
810
- **md,
811
- "doc_key": doc_info.get("doc_key"),
812
- "law_name": doc_info.get("law_name") or md.get("law_name"),
813
- "law_type": doc_info.get("law_type") or md.get("law_type"),
814
- "source": doc_info.get("source") or md.get("source"),
815
- },
816
- "doc_key": str(doc_info.get("doc_key") or ""),
817
- "doc_score": float(doc_info.get("rrf_score", 0.0) or 0.0),
818
- }
819
 
820
 
821
- def _build_doc_candidates(doc_info: Dict[str, Any], graph: Dict[str, Any], *, include_doc_sketch: bool = False) -> List[Dict[str, Any]]:
822
  node_idx = _node_index(graph)
823
- ids: List[str] = []
824
- if include_doc_sketch and doc_info.get("doc_sketch_node_id"):
825
- ids.append(str(doc_info.get("doc_sketch_node_id")))
826
- ids.extend(doc_info.get("article_bundle_ids") or [])
827
- ids.extend(doc_info.get("evidence_ids") or [])
828
-
829
- out: List[Dict[str, Any]] = []
830
  seen: Set[str] = set()
831
- for nid in ids:
832
- if nid in seen or nid not in node_idx:
 
833
  continue
834
- seen.add(nid)
835
- out.append(_build_passage(node_idx[nid], doc_info, graph))
 
 
 
 
 
 
 
836
  return out
837
 
838
 
839
- def _article_bundle_passage(doc_info: Dict[str, Any], article: str, graph: Dict[str, Any]) -> Optional[Dict[str, Any]]:
 
 
 
 
 
 
840
  node_idx = _node_index(graph)
841
- bundle_id = str((doc_info.get("article_to_bundle_id") or {}).get(article) or "")
842
- if not bundle_id or bundle_id not in node_idx:
843
- return None
844
- return _build_passage(node_idx[bundle_id], doc_info, graph)
845
-
846
 
847
- def _same_article_passages(doc_info: Dict[str, Any], article: str, graph: Dict[str, Any]) -> List[Dict[str, Any]]:
848
- node_idx = _node_index(graph)
849
- ids = list((doc_info.get("article_to_evidence_ids") or {}).get(article) or [])
850
- out: List[Dict[str, Any]] = []
851
- for nid in ids:
852
- node = node_idx.get(str(nid))
853
  if not node:
854
  continue
855
- out.append(_build_passage(node, doc_info, graph))
856
- return out
857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
 
859
- def _find_doc_info(doc_groups: List[Dict[str, Any]], doc_key: str) -> Optional[Dict[str, Any]]:
860
- for doc in doc_groups:
861
- if str(doc.get("doc_key") or "") == str(doc_key or ""):
862
- return doc
863
- return None
864
 
 
 
 
 
 
865
 
866
  # =========================
867
- # Route-specific retrieval
868
  # =========================
869
 
870
- def _heading_list_route(question: str, graph: Dict[str, Any], doc_candidates: List[Dict[str, Any]], query_profile: Dict[str, Any], question_vec: List[float], final_top_k: int) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
871
- article_candidates: List[Dict[str, Any]] = []
872
- for doc in doc_candidates:
873
- for node_id in doc.get("article_bundle_ids") or []:
874
- node = _node_index(graph).get(str(node_id))
875
- if node:
876
- article_candidates.append(_build_passage(node, doc, graph))
877
-
878
- ranked_articles = _rank_passages_multifield(question, article_candidates, question_vec=question_vec, query_profile=query_profile)
879
- if not ranked_articles:
880
- return [], []
881
-
882
- top_article = ranked_articles[0]
883
- md = dict(top_article.get("metadata") or {})
884
- doc_info = _find_doc_info(doc_candidates, str(top_article.get("doc_key") or ""))
885
- article = str(md.get("article") or "").strip()
886
-
887
- final_passages: List[Dict[str, Any]] = [top_article]
888
- if doc_info and article:
889
- for p in _same_article_passages(doc_info, article, graph):
890
- if str(p.get("node_id") or "") == str(top_article.get("node_id") or ""):
891
  continue
892
- final_passages.append(p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
893
 
894
- seen: Set[str] = set()
895
- deduped: List[Dict[str, Any]] = []
896
- for item in final_passages:
897
- nid = str(item.get("node_id") or "")
898
- if nid in seen:
899
- continue
900
- seen.add(nid)
901
- deduped.append(item)
902
- return ranked_articles, deduped[:final_top_k]
903
 
 
 
 
 
 
904
 
905
- def _version_change_route(question: str, graph: Dict[str, Any], doc_candidates: List[Dict[str, Any]], query_profile: Dict[str, Any], question_vec: List[float], cross_top_k: int, final_top_k: int) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
906
- change_terms = [str(x).lower() for x in (query_profile.get("change_terms") or [])]
907
- candidates: List[Dict[str, Any]] = []
908
- for doc in doc_candidates:
909
- for p in _build_doc_candidates(doc, graph):
910
- text = (_norm_space(str(p.get("self_retrieval_text") or "")).lower() + " " + _norm_space(str(p.get("heading_text") or "")).lower())
911
- if any(term in text for term in change_terms):
912
- candidates.append(p)
913
- if not candidates:
914
- for doc in doc_candidates:
915
- candidates.extend(_build_doc_candidates(doc, graph))
916
- ranked = _rank_passages_multifield(question, candidates, question_vec=question_vec, query_profile=query_profile)
917
- reranked = cross_rerank(question, ranked[:max(cross_top_k, 1)], top_n=min(max(cross_top_k, 1), len(ranked)), query_profile=query_profile)
918
- return ranked, reranked[:final_top_k]
919
-
920
-
921
- def _generic_route(question: str, graph: Dict[str, Any], doc_candidates: List[Dict[str, Any]], query_profile: Dict[str, Any], question_vec: List[float], cross_top_k: int, final_top_k: int) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
922
- filters = query_profile.get("filters") or {}
923
- want_article = _norm_space(str(filters.get("article") or ""))
924
- want_clause = _norm_space(str(filters.get("clause") or ""))
925
- want_point = _norm_space(str(filters.get("point") or ""))
926
 
927
- candidates: List[Dict[str, Any]] = []
928
- for doc in doc_candidates:
929
- for p in _build_doc_candidates(doc, graph):
930
- md = dict(p.get("metadata") or {})
931
- artifact = str(md.get("artifact_type") or "")
932
- if want_article:
933
- article = _norm_space(str(md.get("article") or ""))
934
- if artifact == "doc_sketch":
935
- continue
936
- if want_clause or want_point:
937
- if article.lower() != want_article.lower():
938
- continue
939
- else:
940
- if article.lower() != want_article.lower() and artifact != "article_bundle":
941
- continue
942
- if want_clause and _norm_space(str(md.get("clause") or "")).lower() != want_clause.lower():
 
 
 
 
 
 
 
943
  continue
944
- if want_point and _norm_space(str(md.get("point") or "")).lower() != want_point.lower():
 
 
 
 
945
  continue
946
- candidates.append(p)
947
-
948
- if not candidates:
949
- for doc in doc_candidates:
950
- candidates.extend(_build_doc_candidates(doc, graph))
951
-
952
- ranked = _rank_passages_multifield(question, candidates, question_vec=question_vec, query_profile=query_profile)
953
- reranked = cross_rerank(question, ranked[:max(cross_top_k, 1)], top_n=min(max(cross_top_k, 1), len(ranked)), query_profile=query_profile)
954
-
955
- route = str(query_profile.get("route") or "")
956
- if reranked and route in {"direct_reference", "condition_circumstance", "factoid", "document_focus"}:
957
- top = reranked[0]
958
- md = dict(top.get("metadata") or {})
959
- article = str(md.get("article") or "").strip()
960
- artifact = str(md.get("artifact_type") or "")
961
- doc_info = _find_doc_info(doc_candidates, str(top.get("doc_key") or ""))
962
- extras: List[Dict[str, Any]] = []
963
- if doc_info and article and artifact != "article_bundle":
964
- bundle = _article_bundle_passage(doc_info, article, graph)
965
- if bundle:
966
- extras.append(bundle)
967
- if route == "condition_circumstance" and query_profile.get("wants_list_answer"):
968
- extras.extend(_same_article_passages(doc_info, article, graph))
969
- merged = []
970
- seen: Set[str] = set()
971
- for item in reranked + extras:
972
- nid = str(item.get("node_id") or "")
973
- if nid in seen:
974
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
975
  seen.add(nid)
976
- merged.append(item)
977
- reranked = merged
 
 
 
 
 
 
 
 
 
 
 
 
 
978
 
979
- return ranked, reranked[:final_top_k]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
980
 
 
 
 
 
 
981
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
982
  # =========================
983
- # Main public API
984
  # =========================
985
 
986
- def retrieve_with_graph(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
987
  question: str,
988
  graph: Dict[str, Any],
 
989
  *,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
990
  filters: Optional[Dict[str, Any]] = None,
991
  qdrant_top_k: Optional[int] = None,
992
  graph_hops: int = 2,
@@ -994,84 +1212,84 @@ def retrieve_with_graph(
994
  final_top_k: Optional[int] = None,
995
  cross_top_k: Optional[int] = None,
996
  ) -> Dict[str, Any]:
997
- _ = qdrant_top_k
998
- _ = graph_hops
999
- _ = max_graph_nodes
1000
-
1001
- question = _norm_space(question)
1002
- query_profile = infer_query_profile(question)
1003
- merged_filters = dict(query_profile.get("filters") or {})
1004
- for k, v in (filters or {}).items():
1005
- if v not in (None, ""):
1006
- merged_filters[k] = v
1007
- if merged_filters:
1008
- query_profile["filters"] = merged_filters
1009
-
1010
- question_vec = _question_embedding(question)
1011
- doc_candidates = rank_documents_by_sketch_rrf(
1012
  question,
1013
  graph,
1014
- top_k=_DOCUMENT_TOP_K,
1015
- question_vec=question_vec,
1016
- filters=merged_filters,
1017
- query_profile=query_profile,
1018
  )
1019
- doc_seed_stage = str((doc_candidates[0].get("doc_seed_stage") if doc_candidates else "none") or "none")
1020
-
1021
- final_limit = max(1, int(final_top_k or _FINAL_TOP_K))
1022
- cross_limit = max(1, int(cross_top_k or (_PASSAGES_PER_DOC * max(1, len(doc_candidates)))))
1023
-
1024
- route = str(query_profile.get("route") or "factoid")
1025
- if route == "heading_list":
1026
- candidate_pool, final_passages = _heading_list_route(question, graph, doc_candidates, query_profile, question_vec, final_limit)
1027
- pipeline = f"document_seed[{doc_seed_stage}] -> article_bundle_rank -> expand_same_article -> topk"
1028
- elif route == "version_change":
1029
- candidate_pool, final_passages = _version_change_route(question, graph, doc_candidates, query_profile, question_vec, cross_limit, final_limit)
1030
- pipeline = f"document_seed[{doc_seed_stage}] -> change_candidates -> multifield_hybrid -> cross_rerank -> topk"
1031
- else:
1032
- candidate_pool, final_passages = _generic_route(question, graph, doc_candidates, query_profile, question_vec, cross_limit, final_limit)
1033
- pipeline = f"document_seed[{doc_seed_stage}] -> provision/article candidates -> multifield_hybrid -> cross_rerank -> completion -> topk"
1034
-
1035
- for idx, passage in enumerate(final_passages, start=1):
1036
- passage["rank"] = idx
1037
- passage["final_score"] = float(
1038
- passage.get("cross_score", passage.get("hybrid_score", 0.0)) or 0.0
1039
- )
1040
 
1041
- doc_groups: List[Dict[str, Any]] = []
1042
- for doc in doc_candidates:
1043
- items = [p for p in final_passages if str(p.get("doc_key") or "") == str(doc.get("doc_key") or "")]
1044
- doc_groups.append(
1045
- {
1046
- "doc_key": doc.get("doc_key"),
1047
- "doc_score": float(doc.get("rrf_score", 0.0) or 0.0),
1048
- "law_name": doc.get("law_name"),
1049
- "source": doc.get("source"),
1050
- "items": items,
1051
- "doc_sketch": doc.get("doc_sketch"),
1052
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
1053
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1054
 
1055
  return {
1056
- "question": question,
1057
- "mode": f"intent_route::{route}",
1058
- "filters": merged_filters,
1059
- "qdrant_top_k": None,
1060
- "final_top_k": final_limit,
1061
- "cross_top_k": cross_limit,
1062
- "seed_candidates": doc_candidates,
1063
- "doc_groups": doc_groups,
1064
  "candidate_pool": candidate_pool,
1065
  "passages": final_passages,
1066
- "query_profile": {
1067
- "pipeline": pipeline,
1068
- "route": route,
1069
- "document_top_k": _DOCUMENT_TOP_K,
1070
- "passages_per_doc": _PASSAGES_PER_DOC,
1071
- "uses_qdrant": False,
1072
- "uses_graph_summary_nodes": False,
1073
- "intent_terms": query_profile.get("intent_terms") or [],
1074
- "filters": merged_filters,
1075
- "document_seed_stage": doc_seed_stage,
1076
- },
1077
  }
 
4
  import logging
5
  import math
6
  import re
7
+ from typing import Any, Dict, List, Optional, Set, Tuple
8
+
9
+ from src.app.settings import settings
10
+ from src.rag.auto_filter import infer_query_profile
11
+ from src.rag.graph_builder import (
12
+ collect_amendment_source_nodes,
13
+ collect_subtree_nodes,
14
+ collect_subtree_text,
15
+ )
16
+ from src.rag.hybrid import bm25_score, extract_topic_phrases, tokenize
17
  from src.rag.openai_clients import get_embedings
18
  from src.rag.rerank_cross import cross_rerank
19
 
20
  logger = logging.getLogger(__name__)
21
 
 
 
 
 
22
  _DOC_EMBED_CACHE: Dict[str, List[float]] = {}
23
+ _TEXT_EMBED_CACHE: Dict[str, List[float]] = {}
24
  _QUESTION_EMBED_CACHE: Dict[str, List[float]] = {}
25
 
26
 
27
  # =========================
28
  # Basic helpers
29
  # =========================
30
+ def _sanitize_official_title(doc_type: str, official_title: str, issuing_agency: str) -> str:
31
+ title = _norm_space(official_title)
32
+ dtype = _norm_space(doc_type).upper()
33
+ agency = _norm_space(issuing_agency)
34
+
35
+ if not title:
36
+ return ""
37
+
38
+ if dtype and title.upper() == dtype:
39
+ return ""
40
+
41
+ if agency and title.upper().endswith(agency.upper()):
42
+ title = _norm_space(title[: -len(agency)].strip(" -,:;"))
43
+
44
+ title = re.sub(r"\s{2,}", " ", title).strip()
45
+ return title
46
+
47
+
48
+ def _sanitize_issuing_agency(issuing_agency: str, official_title: str) -> str:
49
+ agency = _norm_space(issuing_agency)
50
+ title = _norm_space(official_title)
51
+
52
+ if not agency:
53
+ return ""
54
+
55
+ if title and agency.upper() == title.upper():
56
+ return ""
57
+
58
+ if title and agency.upper() in title.upper():
59
+ return ""
60
+
61
+ return agency
62
 
63
  def _norm_space(text: str) -> str:
64
  return " ".join((text or "").split()).strip()
 
68
  return hashlib.sha1(_norm_space(text).encode("utf-8")).hexdigest()
69
 
70
 
71
+ def _question_embedding(question: str) -> List[float]:
72
+ q = _norm_space(question)
73
+ key = _text_cache_key(q)
74
+ cached = _QUESTION_EMBED_CACHE.get(key)
75
+ if cached is not None:
76
+ return cached
77
+ vec = list(get_embedings().embed_query(q))
78
+ _QUESTION_EMBED_CACHE[key] = vec
79
+ return vec
80
+
81
+
82
+ def _batch_embed_texts(texts: List[str], *, cache: Dict[str, List[float]]) -> Dict[str, List[float]]:
83
+ out: Dict[str, List[float]] = {}
84
+ misses: List[Tuple[str, str]] = []
85
+
86
+ for text in texts:
87
+ key = _text_cache_key(text)
88
+ if key in cache:
89
+ out[key] = cache[key]
90
+ else:
91
+ misses.append((key, text))
92
+
93
+ if misses:
94
+ vectors = get_embedings().embed_documents([text for _, text in misses])
95
+ for (key, _), vec in zip(misses, vectors):
96
+ cache[key] = list(vec)
97
+ out[key] = cache[key]
98
+
99
+ return out
100
 
101
 
102
  def _cosine(a: List[float], b: List[float]) -> float:
 
126
  return [(v - lo) / (hi - lo) for v in values]
127
 
128
 
129
+ def _rrf_merge(rank_lists: List[List[str]], *, k: int = 60) -> Dict[str, float]:
130
+ out: Dict[str, float] = {}
131
+ for ranked in rank_lists:
132
+ for rank, item_id in enumerate(ranked, start=1):
133
+ if not item_id:
134
+ continue
135
+ out[item_id] = out.get(item_id, 0.0) + 1.0 / (k + rank)
136
+ return out
137
+
138
+
139
+ def _sorted_ids_by_score(items: List[Dict[str, Any]], score_key: str) -> List[str]:
140
+ ranked = sorted(items, key=lambda x: float(x.get(score_key, 0.0) or 0.0), reverse=True)
141
+ out: List[str] = []
142
+ for item in ranked:
143
+ score = float(item.get(score_key, 0.0) or 0.0)
144
+ if score <= 0.0:
145
+ continue
146
+ item_id = str(item.get("id") or item.get("node_id") or "")
147
+ if item_id:
148
+ out.append(item_id)
149
+ return out
150
+
151
+
152
+ def _safe_int(value: Any, default: int = 0) -> int:
153
+ try:
154
+ if value in (None, ""):
155
+ return default
156
+ return int(value)
157
+ except Exception:
158
+ return default
159
+
160
+
161
+ # =========================
162
+ # Query signal extraction
163
+ # =========================
164
+
165
+ _DOC_NUMBER_RE = re.compile(r"\b\d{1,4}/\d{4}/[A-ZĐ\-]+\b", re.IGNORECASE)
166
+ _YEAR_RE = re.compile(r"\b(19\d{2}|20\d{2})\b")
167
+
168
+ _DOC_TYPE_PATTERNS = {
169
+ "bộ luật": "Bộ luật",
170
+ "luật": "Luật",
171
+ "nghị định": "Nghị định",
172
+ "thông tư": "Thông tư",
173
+ "quyết định": "Quyết định",
174
+ "chỉ thị": "Chỉ thị",
175
+ "nghị quyết": "Nghị quyết",
176
+ "công điện": "Công điện",
177
+ }
178
+
179
+ _DATE_INTENT_TERMS = [
180
+ "có hiệu lực",
181
+ "hiệu lực",
182
+ "từ ngày nào",
183
+ "ngày nào",
184
+ "ban hành ngày nào",
185
+ "ngày ban hành",
186
+ "ngày ký",
187
+ ]
188
+
189
+
190
+ def _compact_upper(text: str) -> str:
191
+ return re.sub(r"[^A-Z0-9Đ]+", "", str(text or "").upper())
192
+
193
+ def _extract_query_signals(question: str) -> Dict[str, str]:
194
+ q = _norm_space(question)
195
+ q_lower = q.lower()
196
+
197
+ doc_number = ""
198
+ m = _DOC_NUMBER_RE.search(q.upper())
199
+ if m:
200
+ doc_number = _norm_space(m.group(0)).upper()
201
+
202
+ doc_type = ""
203
+ for raw, canonical in _DOC_TYPE_PATTERNS.items():
204
+ if raw in q_lower:
205
+ doc_type = canonical
206
+ break
207
+
208
+ agency_hint = ""
209
+ if doc_number:
210
+ suffix = doc_number.split("/")[-1].upper()
211
+ agency_hint = suffix
212
+
213
+ if not doc_type:
214
+ if suffix.startswith("TT-"):
215
+ doc_type = "Thông tư"
216
+ elif suffix.startswith("QĐ-"):
217
+ doc_type = "Quyết định"
218
+ elif suffix.startswith("NQ-"):
219
+ doc_type = "Nghị quyết"
220
+ elif suffix.startswith("CĐ-"):
221
+ doc_type = "Công điện"
222
+ elif suffix.startswith("NĐ-"):
223
+ doc_type = "Nghị định"
224
+ elif suffix.startswith("CT-"):
225
+ doc_type = "Chỉ thị"
226
+
227
+ year = ""
228
+ y = _YEAR_RE.search(q)
229
+ if y:
230
+ year = y.group(1)
231
+
232
+ date_intent = ""
233
+ for term in _DATE_INTENT_TERMS:
234
+ if term in q_lower:
235
+ date_intent = term
236
+ break
237
+
238
+ return {
239
+ "doc_number": doc_number,
240
+ "doc_type": doc_type,
241
+ "agency_hint": agency_hint,
242
+ "year": year,
243
+ "date_intent": date_intent,
244
+ }
245
+
246
+ # =========================
247
+ # Graph/node helpers
248
+ # =========================
249
+
250
  def _node_index(graph: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
251
  idx = graph.get("node_index", {}) or {}
252
  if idx:
253
  return idx
 
 
 
 
254
  out: Dict[str, Dict[str, Any]] = {}
255
+ for node in list(graph.get("nodes") or []):
256
  node_id = str(node.get("node_id") or "").strip()
257
  if node_id:
258
  out[node_id] = node
259
+ graph["node_index"] = out
260
  return out
261
 
262
 
263
+ def _node_md(node: Dict[str, Any]) -> Dict[str, Any]:
264
+ return dict(node.get("metadata") or {})
265
 
266
 
267
  def _node_type(node: Dict[str, Any]) -> str:
268
+ return str(node.get("node_type") or _node_md(node).get("node_type") or "").strip().lower()
269
 
270
 
271
+ def _node_text(node: Dict[str, Any]) -> str:
272
+ return _norm_space(str(node.get("text") or node.get("retrieval_text") or ""))
 
 
 
 
273
 
274
 
275
+ def _artifact_type(node: Dict[str, Any]) -> str:
276
+ return str(_node_md(node).get("artifact_type") or "evidence").strip().lower()
 
 
 
 
277
 
278
 
279
+ def _path_label(md: Dict[str, Any]) -> str:
280
+ for key in ["path_title", "title", "heading_title", "article", "clause", "point", "label"]:
281
+ val = md.get(key)
282
+ if val is not None and str(val).strip():
283
+ return str(val).strip()
284
+ return "-"
 
 
 
 
 
285
 
286
 
287
+ def _first_sentences(text: str, *, limit: int = 320) -> str:
288
  clean = _norm_space(text)
289
  if len(clean) <= limit:
290
  return clean
291
  return clean[: max(0, limit - 3)].rstrip() + "..."
292
 
293
 
294
+ def _to_node_id_list(values: Any) -> List[str]:
295
+ out: List[str] = []
296
+ for v in list(values or []):
297
+ if isinstance(v, dict):
298
+ nid = str(v.get("node_id") or v.get("id") or "").strip()
299
+ if nid:
300
+ out.append(nid)
301
  else:
302
+ nid = str(v or "").strip()
303
+ if nid:
304
+ out.append(nid)
 
 
 
 
 
305
  return out
306
 
307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  # =========================
309
+ # Doc catalog
310
  # =========================
311
 
312
+ def _pick_best_doc_metadata(nodes: List[Dict[str, Any]]) -> Dict[str, Any]:
313
+ """
314
+ Ưu tiên metadata theo đúng cấp document:
315
+ 1) node_type=document
316
+ 2) artifact_type=doc_sketch
317
+ 3) evidence/article_bundle đầu tiên còn lại
318
+ """
319
+ if not nodes:
320
+ return {}
321
+
322
+ def sort_key(node: Dict[str, Any]) -> Tuple[int, int]:
323
+ ntype = _node_type(node)
324
+ art = _artifact_type(node)
325
+ md = _node_md(node)
326
+ order = _safe_int(md.get("order_index"), 0)
327
+
328
+ if ntype == "document":
329
+ return (0, order)
330
+ if art == "doc_sketch":
331
+ return (1, order)
332
+ if art == "evidence":
333
+ return (2, order)
334
+ if art == "article_bundle":
335
+ return (3, order)
336
+ return (9, order)
337
+
338
+ chosen = sorted(nodes, key=sort_key)[0]
339
+ return _node_md(chosen)
340
 
341
 
342
  def _build_doc_catalog(graph: Dict[str, Any]) -> List[Dict[str, Any]]:
 
 
 
 
 
343
  node_idx = _node_index(graph)
344
+
345
+ # Chỉ bucket theo doc_id thật. Không dùng official_title/file_stem/law_name để đoán.
346
  buckets: Dict[str, Dict[str, Any]] = {}
347
 
348
  for node_id, node in node_idx.items():
349
+ md = _node_md(node)
350
+ doc_id = str(md.get("doc_id") or "").strip()
351
+ if not doc_id:
352
  continue
353
+
354
  bucket = buckets.setdefault(
355
+ doc_id,
356
  {
357
+ "id": doc_id,
358
+ "doc_key": doc_id,
359
+ "doc_id": doc_id,
360
+ "nodes": [],
361
+ "reference_node_ids_strict": [],
362
+ "reference_node_ids": [],
363
+ "evidence_node_ids": [],
364
+ "member_node_ids": [],
365
+ "doc_sketch_node_id": "",
 
 
 
 
 
 
 
 
 
 
 
 
366
  },
367
  )
368
+
369
+ bucket["nodes"].append(node)
370
+ bucket["member_node_ids"].append(node_id)
371
+
372
+ ntype = _node_type(node)
373
+ art = _artifact_type(node)
374
+
375
+ if art == "doc_sketch":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  bucket["doc_sketch_node_id"] = node_id
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
+ if art == "evidence":
379
+ bucket["evidence_node_ids"].append(node_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
+ if ntype in {"article", "clause", "point"}:
382
+ bucket["reference_node_ids_strict"].append(node_id)
383
+ bucket["reference_node_ids"].append(node_id)
384
+ elif ntype in {"section", "item"}:
385
+ bucket["reference_node_ids"].append(node_id)
386
 
387
+ docs: List[Dict[str, Any]] = []
388
 
389
+ for doc_id, bucket in buckets.items():
390
+ chosen_md = _pick_best_doc_metadata(bucket["nodes"])
391
 
392
+ doc_type = _norm_space(str(chosen_md.get("doc_type") or chosen_md.get("law_type") or ""))
393
+ issuing_agency = _norm_space(str(chosen_md.get("issuing_agency") or chosen_md.get("source") or ""))
394
+ official_title = _norm_space(str(chosen_md.get("official_title") or chosen_md.get("law_name") or ""))
 
 
 
 
 
 
 
 
395
 
396
+ official_title = _sanitize_official_title(doc_type, official_title, issuing_agency)
397
+ issuing_agency = _sanitize_issuing_agency(issuing_agency, official_title)
398
 
399
+ law_name = official_title or doc_id
400
+ doc_number = _norm_space(str(chosen_md.get("doc_number") or "")).upper()
401
+ year = _safe_int(chosen_md.get("year"), 0)
402
+ date_raw = _norm_space(str(chosen_md.get("date_raw") or ""))
 
 
 
 
403
 
404
+ doc_sketch = ""
405
+ if bucket["doc_sketch_node_id"]:
406
+ doc_sketch_node = node_idx.get(bucket["doc_sketch_node_id"])
407
+ if doc_sketch_node:
408
+ doc_sketch = _node_text(doc_sketch_node)
409
 
410
+ docs.append(
411
+ {
412
+ "id": doc_id,
413
+ "doc_key": doc_id,
414
+ "doc_id": doc_id,
415
+ "official_title": official_title,
416
+ "law_name": law_name,
417
+ "doc_type": doc_type,
418
+ "law_type": doc_type,
419
+ "source": issuing_agency,
420
+ "issuing_agency": issuing_agency,
421
+ "doc_number": doc_number,
422
+ "year": year,
423
+ "date_raw": date_raw,
424
+ "doc_sketch": doc_sketch,
425
+ "reference_node_ids_strict": list(dict.fromkeys(bucket["reference_node_ids_strict"])),
426
+ "reference_node_ids": list(dict.fromkeys(bucket["reference_node_ids"])),
427
+ "evidence_node_ids": list(dict.fromkeys(bucket["evidence_node_ids"])),
428
+ "member_node_ids": list(dict.fromkeys(bucket["member_node_ids"])),
429
+ "doc_sketch_node_id": bucket["doc_sketch_node_id"],
430
+ }
431
+ )
432
 
433
+ docs.sort(key=lambda x: str(x.get("doc_id") or ""))
434
+ return docs
435
 
 
 
 
 
436
 
437
+ # =========================
438
+ # Metadata-first shortlist
439
+ # =========================
440
+
441
+ def _metadata_exactish_score(query_signals: Dict[str, str], doc: Dict[str, Any]) -> Dict[str, float]:
442
+ doc_number = str(doc.get("doc_number") or "").upper()
443
+ doc_type = _norm_space(str(doc.get("doc_type") or ""))
444
+ issuing_agency = _norm_space(str(doc.get("issuing_agency") or ""))
445
+ year = str(doc.get("year") or "")
446
+
447
+ q_doc_number = str(query_signals.get("doc_number") or "").upper()
448
+ q_doc_type = _norm_space(str(query_signals.get("doc_type") or ""))
449
+ q_agency = _compact_upper(query_signals.get("agency_hint") or "")
450
+ q_year = str(query_signals.get("year") or "")
451
+
452
+ doc_number_exact = 0.0
453
+ if q_doc_number and doc_number:
454
+ if q_doc_number == doc_number:
455
+ doc_number_exact = 1.0
456
+ elif q_doc_number in doc_number or doc_number in q_doc_number:
457
+ doc_number_exact = 0.85
458
+ else:
459
+ q_parts = q_doc_number.split("/")
460
+ d_parts = doc_number.split("/")
461
+ if len(q_parts) >= 3 and len(d_parts) >= 3:
462
+ # cùng năm + cùng hậu tố văn bản
463
+ if q_parts[1] == d_parts[1] and q_parts[2] == d_parts[2]:
464
+ doc_number_exact = 0.35
465
+
466
+ doc_type_exact = 0.0
467
+ if q_doc_type and doc_type and q_doc_type.lower() == doc_type.lower():
468
+ doc_type_exact = 1.0
469
+
470
+ agency_exact = 0.0
471
+ if q_agency:
472
+ doc_agency_compact = _compact_upper(issuing_agency)
473
+ doc_number_suffix = _compact_upper(doc_number.split("/")[-1] if doc_number else "")
474
+ if q_agency == doc_agency_compact or q_agency == doc_number_suffix:
475
+ agency_exact = 1.0
476
+ elif q_agency and (q_agency in doc_agency_compact or q_agency in doc_number_suffix):
477
+ agency_exact = 0.7
478
+
479
+ year_exact = 0.0
480
+ if q_year and year and q_year == year:
481
+ year_exact = 1.0
482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  return {
484
+ "doc_number_exact": doc_number_exact,
485
+ "doc_type_exact": doc_type_exact,
486
+ "agency_exact": agency_exact,
487
+ "year_exact": year_exact,
 
488
  }
489
 
490
 
491
+ def _metadata_shortlist_docs(question: str, docs: List[Dict[str, Any]], *, shortlist_k: int) -> Tuple[List[Dict[str, Any]], Dict[str, str]]:
492
+ query_signals = _extract_query_signals(question)
493
+ rescored: List[Dict[str, Any]] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
 
 
 
 
 
 
 
495
  for doc in docs:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  item = dict(doc)
497
+ scores = _metadata_exactish_score(query_signals, item)
498
+ item.update(scores)
499
+ item["metadata_shortlist_score"] = (
500
+ 3.0 * scores["doc_number_exact"]
501
+ + 1.5 * scores["agency_exact"]
502
+ + 0.8 * scores["doc_type_exact"]
503
+ + 0.3 * scores["year_exact"]
504
+ )
505
+ item["query_signals"] = query_signals
506
+ rescored.append(item)
507
 
508
+ rescored.sort(key=lambda x: float(x.get("metadata_shortlist_score", 0.0)), reverse=True)
 
509
 
510
+ if not rescored:
511
+ return [], query_signals
512
 
513
+ if float(rescored[0].get("metadata_shortlist_score", 0.0)) <= 0.0:
514
+ return rescored[: max(1, shortlist_k)], query_signals
 
 
 
 
 
 
 
 
 
515
 
516
+ return rescored[: max(1, shortlist_k)], query_signals
 
 
 
 
517
 
 
 
 
 
 
518
 
519
+ # =========================
520
+ # Top-doc ranking
521
+ # =========================
522
+
523
+ def _doc_title_text(doc: Dict[str, Any]) -> str:
524
+ return _norm_space(str(doc.get("official_title") or doc.get("law_name") or ""))
525
+
526
+
527
+ def rank_top_documents_by_official_title(question: str, graph: Dict[str, Any], *, top_k: Optional[int] = None) -> Tuple[List[Dict[str, Any]], Dict[str, str], List[str]]:
528
+ docs = _build_doc_catalog(graph)
529
+ if not docs:
530
+ return [], {}, []
531
+
532
+ top_k = int(top_k or getattr(settings, "doc_top_k", 3) or 3)
533
+ shortlist_k = max(top_k * 8, 20)
534
+
535
+ metadata_shortlist, query_signals = _metadata_shortlist_docs(question, docs, shortlist_k=shortlist_k)
536
+ topic_phrases = extract_topic_phrases(question)
537
+
538
+ title_texts = [_doc_title_text(d) for d in metadata_shortlist]
539
+ q_vec = _question_embedding(question)
540
+ title_vecs = _batch_embed_texts(title_texts, cache=_DOC_EMBED_CACHE)
541
+
542
+ scored: List[Dict[str, Any]] = []
543
+ for doc, title_text in zip(metadata_shortlist, title_texts):
544
+ item = dict(doc)
545
+ title_key = _text_cache_key(title_text)
546
+ title_dense = _cosine(q_vec, title_vecs.get(title_key, []))
547
+ title_bm25 = bm25_score(tokenize(question), tokenize(title_text))
548
+
549
+ doc_sketch = _norm_space(str(item.get("doc_sketch") or ""))
550
+ matched_topic_phrases = [
551
+ p for p in topic_phrases
552
+ if p and (p in title_text.lower() or p in doc_sketch.lower())
553
+ ]
554
+ topic_gate_bonus = 0.12 if matched_topic_phrases else 0.0
555
+
556
+ item["title_dense"] = float(title_dense)
557
+ item["title_bm25"] = float(title_bm25)
558
+ item["matched_topic_phrases"] = matched_topic_phrases
559
+ item["topic_gate_bonus"] = topic_gate_bonus
560
+ scored.append(item)
561
+
562
+ dense_norm = _minmax([float(x["title_dense"]) for x in scored])
563
+ bm25_norm = _minmax([float(x["title_bm25"]) for x in scored])
564
+
565
+ for item, dnorm, bnorm in zip(scored, dense_norm, bm25_norm):
566
+ item["title_dense_norm"] = dnorm
567
+ item["title_bm25_norm"] = bnorm
568
+
569
+ rank_doc_number = _sorted_ids_by_score(scored, "doc_number_exact")
570
+ rank_agency = _sorted_ids_by_score(scored, "agency_exact")
571
+ rank_title_dense = _sorted_ids_by_score(scored, "title_dense_norm")
572
+ rank_title_bm25 = _sorted_ids_by_score(scored, "title_bm25_norm")
573
+
574
+ rrf = _rrf_merge(
575
+ [rank_doc_number, rank_agency, rank_title_dense, rank_title_bm25],
576
+ k=60,
577
+ )
578
+
579
+ for item in scored:
580
+ item["title_rrf"] = float(rrf.get(str(item.get("id") or ""), 0.0))
581
+ item["doc_score"] = (
582
+ float(item.get("title_rrf", 0.0))
583
+ + float(item.get("topic_gate_bonus", 0.0))
584
+ + 0.03 * float(item.get("metadata_shortlist_score", 0.0))
585
  )
586
 
587
+ scored.sort(key=lambda x: float(x.get("doc_score", 0.0)), reverse=True)
588
+ return scored[: max(1, top_k)], query_signals, topic_phrases
589
 
590
 
 
 
 
 
 
 
 
 
 
591
 
592
 
593
+ def _hybrid_score(dense: float, bm25: float) -> float:
594
+ alpha = float(getattr(settings, "hybrid_alpha", 0.55) or 0.55)
595
+ bm25_norm = min(1.0, float(bm25) / 3.0)
596
+ return float(alpha * float(dense) + (1.0 - alpha) * bm25_norm)
597
+
598
+
599
+ def _route_case(question: str, query_signals: Dict[str, str]) -> Tuple[str, Dict[str, Any]]:
600
+ profile = infer_query_profile(question)
601
+ explicit_reference = bool(profile.get("explicit_reference"))
602
+ has_doc_number = bool(profile.get("has_doc_number")) or bool(query_signals.get("doc_number"))
603
  route = str(profile.get("route") or "")
604
+
605
+ if explicit_reference or has_doc_number or route in {"direct_reference", "document_focus", "version_change"}:
606
+ return "TH2", profile
607
+ return "TH1", profile
608
+
609
+
610
+ def _score_docs_via_doc_sketch(question: str, docs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
611
+ if not docs:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
  return []
613
 
614
+ q_vec = _question_embedding(question)
615
+ texts: List[str] = []
616
+ items: List[Dict[str, Any]] = []
 
617
 
618
+ for doc in docs:
619
+ sketch = _norm_space(str(doc.get("doc_sketch") or ""))
620
+ descriptor = "\n".join(
621
+ x
622
+ for x in [
623
+ f"Số văn bản: {doc.get('doc_number')}",
624
+ f"Loại văn bản: {doc.get('doc_type')}",
625
+ f"Tiêu đề: {doc.get('official_title') or doc.get('law_name')}",
626
+ f"Cơ quan ban hành: {doc.get('issuing_agency') or doc.get('source')}",
627
+ f"Tóm tắt cấu trúc: {sketch}",
628
+ ]
629
+ if _norm_space(x)
630
+ ).strip()
631
+ if not descriptor:
632
+ continue
633
+ item = dict(doc)
634
+ item["doc_sketch_descriptor"] = descriptor
635
+ items.append(item)
636
+ texts.append(descriptor)
637
 
638
+ vecs = _batch_embed_texts(texts, cache=_TEXT_EMBED_CACHE)
639
  ranked: List[Dict[str, Any]] = []
640
+ for item, descriptor in zip(items, texts):
641
+ key = _text_cache_key(descriptor)
642
+ dense = _cosine(q_vec, vecs.get(key, []))
643
+ bm25 = bm25_score(tokenize(question), tokenize(descriptor))
644
+ item["doc_sketch_dense"] = float(dense)
645
+ item["doc_sketch_bm25"] = float(bm25)
646
+ item["doc_sketch_hybrid"] = _hybrid_score(dense, bm25)
647
+ ranked.append(item)
 
 
 
648
 
649
  ranked.sort(
650
  key=lambda x: (
651
+ float(x.get("doc_sketch_hybrid", 0.0) or 0.0),
652
+ float(x.get("doc_score", 0.0) or 0.0),
653
+ float(x.get("metadata_shortlist_score", 0.0) or 0.0),
 
654
  ),
655
  reverse=True,
656
  )
657
  return ranked
658
 
659
 
660
+ def _select_doc_for_general_question(question: str, docs: List[Dict[str, Any]]) -> Tuple[Optional[Dict[str, Any]], List[Dict[str, Any]], float]:
661
+ ranked = _score_docs_via_doc_sketch(question, docs)
662
+ threshold = float(getattr(settings, "doc_sketch_hybrid_threshold", 0.82) or 0.82)
663
+ if not ranked:
664
+ return None, [], threshold
665
+ top_doc = ranked[0]
666
+ if float(top_doc.get("doc_sketch_hybrid", 0.0) or 0.0) >= threshold:
667
+ return top_doc, ranked, threshold
668
+ return None, ranked, threshold
 
669
 
670
 
671
+ def _score_docs_via_bm25_exact(question: str, docs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
672
+ ranked: List[Dict[str, Any]] = []
673
+ q_tokens = tokenize(question)
674
+ for doc in docs:
675
+ descriptor = "\n".join(
676
+ x
677
+ for x in [
678
+ f"Số văn bản: {doc.get('doc_number')}",
679
+ f"Loại văn bản: {doc.get('doc_type')}",
680
+ f"Tiêu đề: {doc.get('official_title') or doc.get('law_name')}",
681
+ f"Cơ quan ban hành: {doc.get('issuing_agency') or doc.get('source')}",
682
+ ]
683
+ if _norm_space(x)
684
+ ).strip()
685
+ item = dict(doc)
686
+ item["exact_doc_descriptor"] = descriptor
687
+ item["exact_doc_bm25"] = float(bm25_score(q_tokens, tokenize(descriptor)))
688
+ ranked.append(item)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
689
 
690
+ ranked.sort(
691
+ key=lambda x: (
692
+ float(x.get("exact_doc_bm25", 0.0) or 0.0),
693
+ float(x.get("doc_number_exact", 0.0) or 0.0),
694
+ float(x.get("agency_exact", 0.0) or 0.0),
695
+ float(x.get("metadata_shortlist_score", 0.0) or 0.0),
696
+ float(x.get("doc_score", 0.0) or 0.0),
697
+ ),
698
+ reverse=True,
699
  )
700
+ return ranked
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
701
 
702
 
703
+ def _iter_single_doc_passage_nodes(doc: Dict[str, Any], graph: Dict[str, Any]) -> List[str]:
704
  node_idx = _node_index(graph)
705
+ out: List[str] = []
 
 
 
 
 
 
706
  seen: Set[str] = set()
707
+ for node_id in list(doc.get("member_node_ids") or []):
708
+ node = node_idx.get(str(node_id or ""))
709
+ if not node:
710
  continue
711
+ art = _artifact_type(node)
712
+ ntype = _node_type(node)
713
+ if art == "doc_sketch":
714
+ continue
715
+ if art == "article_bundle" or ntype in {"article", "clause", "point", "item", "bullet", "section"}:
716
+ nid = str(node_id)
717
+ if nid not in seen:
718
+ seen.add(nid)
719
+ out.append(nid)
720
  return out
721
 
722
 
723
+ def _build_single_doc_passage_candidates(
724
+ question: str,
725
+ graph: Dict[str, Any],
726
+ doc: Dict[str, Any],
727
+ *,
728
+ top_k: int,
729
+ ) -> List[Dict[str, Any]]:
730
  node_idx = _node_index(graph)
731
+ q_vec = _question_embedding(question)
732
+ candidates: List[Dict[str, Any]] = []
 
 
 
733
 
734
+ for node_id in _iter_single_doc_passage_nodes(doc, graph):
735
+ node = node_idx.get(node_id)
 
 
 
 
736
  if not node:
737
  continue
 
 
738
 
739
+ md = _node_md(node)
740
+ parent_id = str(md.get("parent_id") or "").strip()
741
+ children_ids = [str(x).strip() for x in list(md.get("children_ids") or []) if str(x).strip()][:8]
742
+
743
+ source_node_ids: List[str] = []
744
+ if parent_id and parent_id in node_idx:
745
+ source_node_ids.append(parent_id)
746
+ source_node_ids.append(node_id)
747
+ for cid in children_ids:
748
+ if cid in node_idx and cid not in source_node_ids:
749
+ source_node_ids.append(cid)
750
+
751
+ text_parts: List[str] = []
752
+ for sid in source_node_ids:
753
+ src = node_idx.get(sid)
754
+ if not src:
755
+ continue
756
+ st = _node_text(src)
757
+ if st:
758
+ text_parts.append(st)
759
+
760
+ merged_text = "\n".join(t for t in text_parts if _norm_space(t)).strip()
761
+ if not merged_text:
762
+ continue
763
+
764
+ path_title = _path_label(md)
765
+ retrieval_text = "\n".join(
766
+ x
767
+ for x in [
768
+ f"Văn bản: {doc.get('official_title') or doc.get('law_name')}",
769
+ f"Số văn bản: {doc.get('doc_number')}",
770
+ f"Vị trí pháp lý: {path_title}",
771
+ f"Ngữ cảnh cha-con: {_first_sentences(merged_text, limit=900)}",
772
+ ]
773
+ if _norm_space(x)
774
+ ).strip()
775
+
776
+ key = _text_cache_key(retrieval_text)
777
+ vec = _batch_embed_texts([retrieval_text], cache=_TEXT_EMBED_CACHE).get(key, [])
778
+ dense = _cosine(q_vec, vec)
779
+ bm25 = bm25_score(tokenize(question), tokenize(retrieval_text))
780
+ hybrid = _hybrid_score(dense, bm25)
781
+
782
+ candidates.append(
783
+ {
784
+ "id": f"{doc.get('doc_id')}::{node_id}",
785
+ "node_id": node_id,
786
+ "doc_id": str(doc.get("doc_id") or ""),
787
+ "doc_key": str(doc.get("doc_id") or ""),
788
+ "doc_score": float(doc.get("doc_score", 0.0) or 0.0),
789
+ "text": merged_text,
790
+ "snippet": _first_sentences(merged_text, limit=320),
791
+ "retrieval_text": retrieval_text,
792
+ "rerank_text_short": retrieval_text,
793
+ "metadata": md,
794
+ "path_title": path_title,
795
+ "source_node_ids": source_node_ids,
796
+ "content_dense": dense,
797
+ "content_bm25": bm25,
798
+ "content_hybrid": hybrid,
799
+ }
800
+ )
801
+
802
+ candidates.sort(key=lambda x: float(x.get("content_hybrid", 0.0) or 0.0), reverse=True)
803
+ return candidates[: max(1, top_k)]
804
+
805
+
806
+ def _exact_doc_route(
807
+ question: str,
808
+ graph: Dict[str, Any],
809
+ docs: List[Dict[str, Any]],
810
+ *,
811
+ cross_top_k: int,
812
+ final_top_k: int,
813
+ ) -> Tuple[Optional[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], bool, Optional[str], List[Dict[str, Any]]]:
814
+ ranked_docs = _score_docs_via_bm25_exact(question, docs)
815
+ if not ranked_docs:
816
+ return None, [], [], True, "no_exact_doc_match", []
817
+
818
+ chosen_doc = ranked_docs[0]
819
+ passage_top_k = int(getattr(settings, "th2_passage_top_k", max(cross_top_k * 3, 12)) or max(cross_top_k * 3, 12))
820
+ passage_candidates = _build_single_doc_passage_candidates(
821
+ question,
822
+ graph,
823
+ chosen_doc,
824
+ top_k=passage_top_k,
825
+ )
826
+ if not passage_candidates:
827
+ return chosen_doc, [], [], True, "no_exact_doc_passages", ranked_docs
828
+
829
+ reranked = cross_rerank(
830
+ question,
831
+ passage_candidates[: max(1, cross_top_k * 3)],
832
+ top_n=min(max(1, cross_top_k), len(passage_candidates)),
833
+ )
834
+ if not reranked:
835
+ return chosen_doc, passage_candidates, [], True, "cross_empty", ranked_docs
836
 
837
+ best_cross = float(reranked[0].get("cross_score", 0.0) or 0.0)
838
+ min_cross = float(getattr(settings, "cross_rerank_min_score", 0.05) or 0.05)
839
+ if best_cross < min_cross:
840
+ return chosen_doc, passage_candidates, [], True, "cross_score_too_low", ranked_docs
 
841
 
842
+ final_passages = [
843
+ _build_final_bundle_from_grouped_candidate(item, graph)
844
+ for item in reranked[: max(1, final_top_k)]
845
+ ]
846
+ return chosen_doc, passage_candidates, final_passages, False, None, ranked_docs
847
 
848
  # =========================
849
+ # Candidate building
850
  # =========================
851
 
852
+ def _collect_reference_candidates(question: str, graph: Dict[str, Any], docs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
853
+ node_idx = _node_index(graph)
854
+ q_vec = _question_embedding(question)
855
+ out: List[Dict[str, Any]] = []
856
+
857
+ texts_for_embed: List[str] = []
858
+ temp_items: List[Dict[str, Any]] = []
859
+
860
+ for doc in docs:
861
+ doc_id = str(doc.get("doc_id") or "")
862
+ for node_id in list(doc.get("reference_node_ids") or []):
863
+ node = node_idx.get(node_id)
864
+ if not node:
 
 
 
 
 
 
 
 
865
  continue
866
+ md = _node_md(node)
867
+ node_type = _node_type(node)
868
+ path_title = _path_label(md)
869
+ self_text = _first_sentences(_node_text(node), limit=360)
870
+
871
+ anchor_text = "\n".join(
872
+ x for x in [
873
+ f"Văn bản: {doc.get('official_title')}",
874
+ f"Vị trí: {path_title}",
875
+ self_text,
876
+ ] if _norm_space(x)
877
+ ).strip()
878
+
879
+ item = {
880
+ "id": node_id,
881
+ "node_id": node_id,
882
+ "doc_id": doc_id,
883
+ "doc_key": doc_id,
884
+ "doc_score": float(doc.get("doc_score", 0.0)),
885
+ "doc_title": doc.get("official_title"),
886
+ "doc_number": doc.get("doc_number"),
887
+ "text": _node_text(node),
888
+ "snippet": self_text,
889
+ "metadata": md,
890
+ "node_type": node_type,
891
+ "path_title": path_title,
892
+ "retrieval_text": anchor_text,
893
+ "rerank_text_short": anchor_text,
894
+ "source_node_ids": [node_id],
895
+ }
896
+ temp_items.append(item)
897
+ texts_for_embed.append(anchor_text)
898
 
899
+ vecs = _batch_embed_texts(texts_for_embed, cache=_TEXT_EMBED_CACHE)
 
 
 
 
 
 
 
 
900
 
901
+ for item, text in zip(temp_items, texts_for_embed):
902
+ key = _text_cache_key(text)
903
+ dense = _cosine(q_vec, vecs.get(key, []))
904
+ bm25 = bm25_score(tokenize(question), tokenize(text))
905
+ hybrid = 0.55 * dense + 0.45 * min(1.0, bm25 / 3.0)
906
 
907
+ item["reference_dense"] = dense
908
+ item["reference_bm25"] = bm25
909
+ item["reference_hybrid"] = hybrid
910
+ out.append(item)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911
 
912
+ out.sort(key=lambda x: float(x.get("reference_hybrid", 0.0)), reverse=True)
913
+ return out
914
+
915
+
916
+ def _group_content_candidates_by_siblings(
917
+ question: str,
918
+ graph: Dict[str, Any],
919
+ docs: List[Dict[str, Any]],
920
+ *,
921
+ per_doc_top_k: int,
922
+ ) -> List[Dict[str, Any]]:
923
+ node_idx = _node_index(graph)
924
+ q_vec = _question_embedding(question)
925
+ grouped: List[Dict[str, Any]] = []
926
+
927
+ for doc in docs:
928
+ doc_id = str(doc.get("doc_id") or "")
929
+ seen_groups: Set[Tuple[str, ...]] = set()
930
+ candidates: List[Dict[str, Any]] = []
931
+
932
+ for node_id in list(doc.get("evidence_node_ids") or []):
933
+ node = node_idx.get(node_id)
934
+ if not node:
935
  continue
936
+
937
+ md = _node_md(node)
938
+ sibling_ids = list(md.get("sibling_ids") or [])
939
+ group_ids = tuple(sorted(set([node_id] + sibling_ids)))
940
+ if group_ids in seen_groups:
941
  continue
942
+ seen_groups.add(group_ids)
943
+
944
+ texts: List[str] = []
945
+ path_title = ""
946
+ group_nodes: List[Dict[str, Any]] = []
947
+
948
+ for gid in group_ids:
949
+ gnode = node_idx.get(gid)
950
+ if not gnode:
951
+ continue
952
+ group_nodes.append(gnode)
953
+ gmd = _node_md(gnode)
954
+ if not path_title:
955
+ path_title = _path_label(gmd)
956
+ gtext = _node_text(gnode)
957
+ if gtext:
958
+ texts.append(gtext)
959
+
960
+ if not texts:
 
 
 
 
 
 
 
 
 
961
  continue
962
+
963
+ merged_text = "\n".join(t for t in texts if _norm_space(t)).strip()
964
+ retrieval_text = "\n".join(
965
+ x for x in [
966
+ f"Văn bản: {doc.get('official_title')}",
967
+ f"Vị trí chung: {path_title}",
968
+ f"Nhóm sibling: {_first_sentences(merged_text, limit=700)}",
969
+ ] if _norm_space(x)
970
+ ).strip()
971
+
972
+ dense_key = _text_cache_key(retrieval_text)
973
+ vec = _batch_embed_texts([retrieval_text], cache=_TEXT_EMBED_CACHE).get(dense_key, [])
974
+ dense = _cosine(q_vec, vec)
975
+ bm25 = bm25_score(tokenize(question), tokenize(retrieval_text))
976
+ hybrid = 0.55 * dense + 0.45 * min(1.0, bm25 / 3.0)
977
+
978
+ candidates.append(
979
+ {
980
+ "id": "::".join(group_ids),
981
+ "node_id": group_ids[0],
982
+ "doc_id": doc_id,
983
+ "doc_key": doc_id,
984
+ "doc_score": float(doc.get("doc_score", 0.0)),
985
+ "text": merged_text,
986
+ "snippet": _first_sentences(merged_text, limit=320),
987
+ "retrieval_text": retrieval_text,
988
+ "rerank_text_short": retrieval_text,
989
+ "metadata": dict(_node_md(group_nodes[0])) if group_nodes else {},
990
+ "path_title": path_title,
991
+ "source_node_ids": list(group_ids),
992
+ "content_dense": dense,
993
+ "content_bm25": bm25,
994
+ "content_hybrid": hybrid,
995
+ }
996
+ )
997
+
998
+ candidates.sort(key=lambda x: float(x.get("content_hybrid", 0.0)), reverse=True)
999
+ grouped.extend(candidates[: max(1, per_doc_top_k)])
1000
+
1001
+ return grouped
1002
+
1003
+
1004
+ # =========================
1005
+ # Late expansion
1006
+ # =========================
1007
+
1008
+ def _build_final_bundle_from_anchor(candidate: Dict[str, Any], graph: Dict[str, Any]) -> Dict[str, Any]:
1009
+ node_idx = _node_index(graph)
1010
+ node_id = str(candidate.get("node_id") or "")
1011
+ node = node_idx.get(node_id)
1012
+ md = dict(candidate.get("metadata") or {})
1013
+
1014
+ if not node:
1015
+ out = dict(candidate)
1016
+ out["expanded_node_ids"] = [node_id] if node_id else []
1017
+ out["local_text"] = str(candidate.get("text") or "")
1018
+ out["shared_text"] = f"Văn bản: {md.get('official_title') or md.get('law_name') or ''}"
1019
+ out["final_score"] = float(
1020
+ candidate.get("cross_score", candidate.get("reference_hybrid", candidate.get("content_hybrid", 0.0))) or 0.0
1021
+ )
1022
+ return out
1023
+
1024
+ subtree_ids_raw = collect_subtree_nodes(graph, node_id)
1025
+ amendment_sources_raw = collect_amendment_source_nodes(graph, node_id)
1026
+
1027
+ subtree_ids = _to_node_id_list(subtree_ids_raw)
1028
+ amendment_source_ids = _to_node_id_list(amendment_sources_raw)
1029
+ subtree_text = collect_subtree_text(graph, node_id)
1030
+
1031
+ amendment_texts: List[str] = []
1032
+ for sid in amendment_source_ids:
1033
+ src_node = node_idx.get(sid)
1034
+ if not src_node:
1035
+ continue
1036
+ st = _node_text(src_node)
1037
+ if st:
1038
+ amendment_texts.append(st)
1039
+
1040
+ local_parts: List[str] = []
1041
+ if subtree_text:
1042
+ local_parts.append(subtree_text)
1043
+ if amendment_texts:
1044
+ local_parts.append("Nguồn sửa đổi/bổ sung/bãi bỏ liên quan:\n" + "\n".join(amendment_texts))
1045
+
1046
+ expanded_node_ids: List[str] = []
1047
+ seen: Set[str] = set()
1048
+ for nid in [node_id] + subtree_ids + amendment_source_ids:
1049
+ nid = str(nid or "").strip()
1050
+ if nid and nid not in seen:
1051
  seen.add(nid)
1052
+ expanded_node_ids.append(nid)
1053
+
1054
+ out = dict(candidate)
1055
+ out["expanded_node_ids"] = expanded_node_ids
1056
+ out["local_text"] = "\n\n".join(x for x in local_parts if _norm_space(x)).strip()
1057
+ out["shared_text"] = "\n".join(
1058
+ x for x in [
1059
+ f"Văn bản: {md.get('official_title') or md.get('law_name') or ''}",
1060
+ f"Vị trí: {candidate.get('path_title') or _path_label(md)}",
1061
+ ] if _norm_space(x)
1062
+ ).strip()
1063
+ out["final_score"] = float(
1064
+ candidate.get("cross_score", candidate.get("reference_hybrid", candidate.get("content_hybrid", 0.0))) or 0.0
1065
+ )
1066
+ return out
1067
 
1068
+ def _build_final_bundle_from_grouped_candidate(candidate: Dict[str, Any], graph: Dict[str, Any]) -> Dict[str, Any]:
1069
+ node_idx = _node_index(graph)
1070
+ md = dict(candidate.get("metadata") or {})
1071
+
1072
+ source_node_ids = _to_node_id_list(candidate.get("source_node_ids") or [])
1073
+ source_node_ids = [nid for nid in source_node_ids if nid in node_idx]
1074
+
1075
+ grouped_text = _norm_space(str(candidate.get("text") or ""))
1076
+ grouped_snippet = _norm_space(str(candidate.get("snippet") or ""))
1077
+ path_title = _norm_space(str(candidate.get("path_title") or _path_label(md) or ""))
1078
+
1079
+ amendment_source_ids: List[str] = []
1080
+ seen_amend: Set[str] = set()
1081
+ for nid in source_node_ids:
1082
+ for sid in _to_node_id_list(collect_amendment_source_nodes(graph, nid)):
1083
+ if sid and sid not in seen_amend:
1084
+ seen_amend.add(sid)
1085
+ amendment_source_ids.append(sid)
1086
+
1087
+ amendment_texts: List[str] = []
1088
+ for sid in amendment_source_ids:
1089
+ src_node = node_idx.get(sid)
1090
+ if not src_node:
1091
+ continue
1092
+ st = _node_text(src_node)
1093
+ if st:
1094
+ amendment_texts.append(st)
1095
 
1096
+ local_parts: List[str] = []
1097
+ if grouped_text:
1098
+ local_parts.append(grouped_text)
1099
+ elif grouped_snippet:
1100
+ local_parts.append(grouped_snippet)
1101
 
1102
+ if amendment_texts:
1103
+ local_parts.append("Nguồn sửa đổi/bổ sung/bãi bỏ liên quan:\n" + "\n".join(amendment_texts))
1104
+
1105
+ expanded_node_ids: List[str] = []
1106
+ seen: Set[str] = set()
1107
+ for nid in source_node_ids + amendment_source_ids:
1108
+ nid = str(nid or "").strip()
1109
+ if nid and nid not in seen:
1110
+ seen.add(nid)
1111
+ expanded_node_ids.append(nid)
1112
+
1113
+ out = dict(candidate)
1114
+ out["expanded_node_ids"] = expanded_node_ids
1115
+ out["local_text"] = "\n\n".join(x for x in local_parts if _norm_space(x)).strip()
1116
+ out["shared_text"] = "\n".join(
1117
+ x
1118
+ for x in [
1119
+ f"Văn bản: {md.get('official_title') or md.get('law_name') or ''}",
1120
+ f"Vị trí: {path_title}",
1121
+ ]
1122
+ if _norm_space(x)
1123
+ ).strip()
1124
+ out["final_score"] = float(candidate.get("cross_score", candidate.get("content_hybrid", 0.0)) or 0.0)
1125
+ return out
1126
  # =========================
1127
+ # Routes
1128
  # =========================
1129
 
1130
+ def _reference_route(
1131
+ question: str,
1132
+ graph: Dict[str, Any],
1133
+ docs: List[Dict[str, Any]],
1134
+ *,
1135
+ cross_top_k: int,
1136
+ final_top_k: int,
1137
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], bool, Optional[str], float]:
1138
+ ref_candidates = _collect_reference_candidates(question, graph, docs)
1139
+ if not ref_candidates:
1140
+ return [], [], True, "no_reference_candidates", 0.0
1141
+
1142
+ max_reference_hybrid = float(ref_candidates[0].get("reference_hybrid", 0.0) or 0.0)
1143
+
1144
+ reranked = cross_rerank(
1145
+ question,
1146
+ ref_candidates[: max(1, cross_top_k * 3)],
1147
+ top_n=min(max(1, cross_top_k), len(ref_candidates)),
1148
+ )
1149
+
1150
+ if not reranked:
1151
+ return ref_candidates, [], True, "cross_empty", max_reference_hybrid
1152
+
1153
+ best_cross = float(reranked[0].get("cross_score", 0.0) or 0.0)
1154
+ min_cross = float(getattr(settings, "cross_rerank_min_score", 0.05) or 0.05)
1155
+ if best_cross < min_cross:
1156
+ return ref_candidates, [], True, "cross_score_too_low", max_reference_hybrid
1157
+
1158
+ final_passages = [_build_final_bundle_from_anchor(item, graph) for item in reranked[: max(1, final_top_k)]]
1159
+ return ref_candidates, final_passages, False, None, max_reference_hybrid
1160
+
1161
+ def _content_route(
1162
  question: str,
1163
  graph: Dict[str, Any],
1164
+ docs: List[Dict[str, Any]],
1165
  *,
1166
+ cross_top_k: int,
1167
+ final_top_k: int,
1168
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], bool, Optional[str]]:
1169
+ per_doc_top_k = int(getattr(settings, "content_top_k_per_doc", 3) or 3)
1170
+ content_candidates = _group_content_candidates_by_siblings(
1171
+ question,
1172
+ graph,
1173
+ docs,
1174
+ per_doc_top_k=per_doc_top_k,
1175
+ )
1176
+
1177
+ if not content_candidates:
1178
+ return [], [], True, "no_content_candidates"
1179
+
1180
+ reranked = cross_rerank(
1181
+ question,
1182
+ content_candidates[: max(1, cross_top_k * 3)],
1183
+ top_n=min(max(1, cross_top_k), len(content_candidates)),
1184
+ )
1185
+
1186
+ if not reranked:
1187
+ return content_candidates, [], True, "cross_empty"
1188
+
1189
+ best_cross = float(reranked[0].get("cross_score", 0.0) or 0.0)
1190
+ min_cross = float(getattr(settings, "cross_rerank_min_score", 0.05) or 0.05)
1191
+ if best_cross < min_cross:
1192
+ return content_candidates, [], True, "cross_score_too_low"
1193
+
1194
+ # GIỮ NGUYÊN grouped sibling candidate sau rerank, không rebuild lại theo anchor node
1195
+ final_passages = [
1196
+ _build_final_bundle_from_grouped_candidate(item, graph)
1197
+ for item in reranked[: max(1, final_top_k)]
1198
+ ]
1199
+ return content_candidates, final_passages, False, None
1200
+
1201
+ # =========================
1202
+ # Public API
1203
+ # =========================
1204
+
1205
+ def retrieve_with_graph(
1206
+ question: str,
1207
+ graph: Dict[str, Any],
1208
  filters: Optional[Dict[str, Any]] = None,
1209
  qdrant_top_k: Optional[int] = None,
1210
  graph_hops: int = 2,
 
1212
  final_top_k: Optional[int] = None,
1213
  cross_top_k: Optional[int] = None,
1214
  ) -> Dict[str, Any]:
1215
+ del filters, qdrant_top_k, graph_hops, max_graph_nodes
1216
+
1217
+ final_top_k = int(final_top_k or getattr(settings, "final_top_k", 5) or 5)
1218
+ cross_top_k = int(cross_top_k or getattr(settings, "cross_top_k", 8) or 8)
1219
+
1220
+ top_docs, query_signals, topic_phrases = rank_top_documents_by_official_title(
 
 
 
 
 
 
 
 
 
1221
  question,
1222
  graph,
1223
+ top_k=int(getattr(settings, "doc_top_k", 3) or 3),
 
 
 
1224
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1225
 
1226
+ route_case, query_profile = _route_case(question, query_signals)
1227
+
1228
+ if not top_docs:
1229
+ return {
1230
+ "mode": "no_top_docs",
1231
+ "route_case": route_case,
1232
+ "query_profile": query_profile,
1233
+ "topic_phrases": topic_phrases,
1234
+ "doc_sketch_hybrid_threshold": float(getattr(settings, "doc_sketch_hybrid_threshold", 0.82) or 0.82),
1235
+ "rerank_veto": True,
1236
+ "veto_reason": "no_top_docs",
1237
+ "top_docs": [],
1238
+ "candidate_pool": [],
1239
+ "passages": [],
1240
+ "insufficient_context": True,
1241
+ "query_signals": query_signals,
1242
+ }
1243
+
1244
+ if route_case == "TH2":
1245
+ chosen_doc, candidate_pool, final_passages, veto, veto_reason, exact_doc_ranked = _exact_doc_route(
1246
+ question,
1247
+ graph,
1248
+ top_docs,
1249
+ cross_top_k=cross_top_k,
1250
+ final_top_k=final_top_k,
1251
  )
1252
+ return {
1253
+ "mode": "th2_exact_doc_bm25_route",
1254
+ "route_case": route_case,
1255
+ "query_profile": query_profile,
1256
+ "topic_phrases": topic_phrases,
1257
+ "rerank_veto": veto,
1258
+ "veto_reason": veto_reason,
1259
+ "top_docs": [chosen_doc] if chosen_doc else [],
1260
+ "top_docs_initial": top_docs,
1261
+ "exact_doc_ranked": exact_doc_ranked,
1262
+ "candidate_pool": candidate_pool,
1263
+ "passages": final_passages,
1264
+ "insufficient_context": veto or not final_passages,
1265
+ "query_signals": query_signals,
1266
+ }
1267
+
1268
+ selected_doc, doc_sketch_ranked, doc_sketch_threshold = _select_doc_for_general_question(question, top_docs)
1269
+ docs_for_passages = [selected_doc] if selected_doc else top_docs
1270
+ mode = "th1_doc_sketch_locked_route" if selected_doc else "th1_doc_sketch_fallback_route"
1271
+
1272
+ candidate_pool, final_passages, veto, veto_reason = _content_route(
1273
+ question,
1274
+ graph,
1275
+ docs_for_passages,
1276
+ cross_top_k=cross_top_k,
1277
+ final_top_k=final_top_k,
1278
+ )
1279
 
1280
  return {
1281
+ "mode": mode,
1282
+ "route_case": route_case,
1283
+ "query_profile": query_profile,
1284
+ "topic_phrases": topic_phrases,
1285
+ "doc_sketch_hybrid_threshold": doc_sketch_threshold,
1286
+ "doc_sketch_ranked": doc_sketch_ranked,
1287
+ "top_docs": docs_for_passages,
1288
+ "top_docs_initial": top_docs,
1289
  "candidate_pool": candidate_pool,
1290
  "passages": final_passages,
1291
+ "rerank_veto": veto,
1292
+ "veto_reason": veto_reason,
1293
+ "insufficient_context": veto or not final_passages,
1294
+ "query_signals": query_signals,
 
 
 
 
 
 
 
1295
  }
src/storage/qdrant_store.py CHANGED
@@ -4,8 +4,8 @@ import json
4
  from typing import Any, Dict, List, Optional
5
 
6
  from qdrant_client import QdrantClient
7
- from qdrant_client.http.exceptions import UnexpectedResponse
8
  from qdrant_client.http import models as qm
 
9
  from qdrant_client.http.models import Distance, VectorParams
10
 
11
  from src.app.settings import settings
@@ -21,15 +21,11 @@ def get_qdrant_client() -> QdrantClient:
21
  )
22
 
23
 
24
- def ensure_collection(
25
- client: QdrantClient,
26
- vector_size: int = DEFAULT_VECTOR_SIZE,
27
- ) -> None:
28
  collections = client.get_collections().collections
29
- names = {c.name for c in collections}
30
  if settings.qdrant_collection in names:
31
  return
32
-
33
  client.create_collection(
34
  collection_name=settings.qdrant_collection,
35
  vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE),
@@ -39,74 +35,45 @@ def ensure_collection(
39
  def build_filter(filters: Dict[str, Any]) -> Optional[qm.Filter]:
40
  if not filters:
41
  return None
42
-
43
  must: List[qm.FieldCondition] = []
44
-
45
- for k, v in filters.items():
46
- if v is None or v == "":
47
  continue
48
-
49
- if isinstance(v, (int, float, bool, str)):
50
- must.append(qm.FieldCondition(key=k, match=qm.MatchValue(value=v)))
51
- elif isinstance(v, list) and v:
52
- must.append(qm.FieldCondition(key=k, match=qm.MatchAny(any=v)))
53
-
54
- if not must:
55
- return None
56
-
57
- return qm.Filter(must=must)
58
 
59
 
60
- def upsert_points(
61
- client: QdrantClient,
62
- points: List[qm.PointStruct],
63
- ) -> None:
64
  if not points:
65
  return
66
-
67
- # Qdrant HTTP giới hạn payload request (mặc định thường ~32MB).
68
- # Chia batch để tránh lỗi 400 "JSON payload ... is larger than allowed".
69
- max_batch_bytes = 8 * 1024 * 1024 # 8MB an toàn hơn nhiều so với giới hạn 32MB
70
  max_batch_points = 256
71
 
72
- def _estimate_point_bytes(p: qm.PointStruct) -> int:
73
- payload = getattr(p, "payload", {}) or {}
74
  try:
75
  payload_bytes = len(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
76
  except Exception:
77
  payload_bytes = 0
78
-
79
- vec = getattr(p, "vector", None)
80
- if isinstance(vec, list):
81
- vector_bytes = len(vec) * 4 # float32 xấp xỉ
82
- else:
83
- vector_bytes = 0
84
-
85
- # overhead JSON + id + keys
86
  return payload_bytes + vector_bytes + 2048
87
 
88
  batch: List[qm.PointStruct] = []
89
  batch_bytes = 0
90
-
91
- for p in points:
92
- p_bytes = _estimate_point_bytes(p)
93
-
94
- if batch and (batch_bytes + p_bytes > max_batch_bytes or len(batch) >= max_batch_points):
95
- client.upsert(
96
- collection_name=settings.qdrant_collection,
97
- points=batch,
98
- )
99
  batch = []
100
  batch_bytes = 0
101
-
102
- batch.append(p)
103
- batch_bytes += p_bytes
104
-
105
  if batch:
106
- client.upsert(
107
- collection_name=settings.qdrant_collection,
108
- points=batch,
109
- )
110
 
111
 
112
  def search_qdrant(
@@ -126,8 +93,6 @@ def search_qdrant(
126
  with_vectors=False,
127
  )
128
 
129
- # qdrant-client mới dùng query_points thay cho search.
130
- # Nhưng server cũ (vd 1.9.x) có thể trả 404 cho endpoint query_points.
131
  try:
132
  response = client.query_points(
133
  collection_name=settings.qdrant_collection,
@@ -146,7 +111,6 @@ def search_qdrant(
146
  if getattr(exc, "status_code", None) != 404:
147
  raise
148
 
149
- # Fallback gọi REST search_points (tương thích server cũ)
150
  legacy_response = client.http.search_api.search_points(
151
  collection_name=settings.qdrant_collection,
152
  search_request=qm.SearchRequest(
 
4
  from typing import Any, Dict, List, Optional
5
 
6
  from qdrant_client import QdrantClient
 
7
  from qdrant_client.http import models as qm
8
+ from qdrant_client.http.exceptions import UnexpectedResponse
9
  from qdrant_client.http.models import Distance, VectorParams
10
 
11
  from src.app.settings import settings
 
21
  )
22
 
23
 
24
+ def ensure_collection(client: QdrantClient, vector_size: int = DEFAULT_VECTOR_SIZE) -> None:
 
 
 
25
  collections = client.get_collections().collections
26
+ names = {collection.name for collection in collections}
27
  if settings.qdrant_collection in names:
28
  return
 
29
  client.create_collection(
30
  collection_name=settings.qdrant_collection,
31
  vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE),
 
35
  def build_filter(filters: Dict[str, Any]) -> Optional[qm.Filter]:
36
  if not filters:
37
  return None
 
38
  must: List[qm.FieldCondition] = []
39
+ for key, value in filters.items():
40
+ if value in (None, ""):
 
41
  continue
42
+ if isinstance(value, (int, float, bool, str)):
43
+ must.append(qm.FieldCondition(key=key, match=qm.MatchValue(value=value)))
44
+ elif isinstance(value, list) and value:
45
+ must.append(qm.FieldCondition(key=key, match=qm.MatchAny(any=value)))
46
+ return qm.Filter(must=must) if must else None
 
 
 
 
 
47
 
48
 
49
+ def upsert_points(client: QdrantClient, points: List[qm.PointStruct]) -> None:
 
 
 
50
  if not points:
51
  return
52
+ max_batch_bytes = 8 * 1024 * 1024
 
 
 
53
  max_batch_points = 256
54
 
55
+ def _estimate_point_bytes(point: qm.PointStruct) -> int:
56
+ payload = getattr(point, "payload", {}) or {}
57
  try:
58
  payload_bytes = len(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
59
  except Exception:
60
  payload_bytes = 0
61
+ vector = getattr(point, "vector", None)
62
+ vector_bytes = len(vector) * 4 if isinstance(vector, list) else 0
 
 
 
 
 
 
63
  return payload_bytes + vector_bytes + 2048
64
 
65
  batch: List[qm.PointStruct] = []
66
  batch_bytes = 0
67
+ for point in points:
68
+ point_bytes = _estimate_point_bytes(point)
69
+ if batch and (batch_bytes + point_bytes > max_batch_bytes or len(batch) >= max_batch_points):
70
+ client.upsert(collection_name=settings.qdrant_collection, points=batch)
 
 
 
 
 
71
  batch = []
72
  batch_bytes = 0
73
+ batch.append(point)
74
+ batch_bytes += point_bytes
 
 
75
  if batch:
76
+ client.upsert(collection_name=settings.qdrant_collection, points=batch)
 
 
 
77
 
78
 
79
  def search_qdrant(
 
93
  with_vectors=False,
94
  )
95
 
 
 
96
  try:
97
  response = client.query_points(
98
  collection_name=settings.qdrant_collection,
 
111
  if getattr(exc, "status_code", None) != 404:
112
  raise
113
 
 
114
  legacy_response = client.http.search_api.search_points(
115
  collection_name=settings.qdrant_collection,
116
  search_request=qm.SearchRequest(