Spaces:
Sleeping
Sleeping
ZhangNguyen commited on
Commit ·
63449bd
1
Parent(s): 29347f2
Add benchmark API metrics and query-variant expansion flow
Browse filesFiles changed (10)
98 unmodified lines9910010110210310423 unmodified lines1281291301311321336 unmodified lines14014114214314414551 unmodified lines19719819920098 unmodified linesfrom src.rag.ingestion import upsert_chunksfrom src.storage.qdrant_store import ensure_collection, get_qdrant_clientfrom src.utils.loader import load_documenttry:from src.rag.chunking_legal import semantic_merge_safe23 unmodified linesdef main():parser = argparse.ArgumentParser(description="Ingest legal documents into Qdrant (NO OCR).")parser.add_argument("--input_dir", type=str, default=settings.normalized_dir)parser.add_argument("--glob", type=str, default=settings.normalized_glob)parser.add_argument("--max_chars", type=int, default=1600)6 unmodified linesargs = parser.parse_args()input_dir = Path(args.input_dir)if not input_dir.exists():raise RuntimeError(f"Missing folder: {input_dir}")51 unmodified linesif __name__ == "__main__":main()98 unmodified lines9910010110210310410523 unmodified lines1291301311321331341351361371381396 unmodified lines14614714814915015115215315451 unmodified lines20620720820998 unmodified linesfrom src.rag.ingestion import upsert_chunksfrom src.storage.qdrant_store import ensure_collection, get_qdrant_clientfrom src.utils.loader import load_documentfrom src.utils.normalize_raw import normalize_raw_to_normalizedtry:from src.rag.chunking_legal import semantic_merge_safe23 unmodified linesdef main():parser = argparse.ArgumentParser(description="Ingest legal documents into Qdrant (NO OCR).")parser.add_argument("--normalize",action="store_true",help="Normalize data/raw -> data/normalized trước khi ingest.",)parser.add_argument("--input_dir", type=str, default=settings.normalized_dir)parser.add_argument("--glob", type=str, default=settings.normalized_glob)parser.add_argument("--max_chars", type=int, default=1600)6 unmodified linesargs = parser.parse_args()if args.normalize:normalize_raw_to_normalized()input_dir = Path(args.input_dir)if not input_dir.exists():raise RuntimeError(f"Missing folder: {input_dir}")51 unmodified linesif __name__ == "__main__":main()
1234567891011121314151617181920212223242526272829303132333435363738394041from __future__ import annotationsfrom typing import Any, Dict, List, Optionalfrom fastapi import APIRouterfrom pydantic import BaseModel, Fieldfrom src.eval.benchmark_metrics import evaluate_rag_responsefrom src.eval.performance_monitor import PerformanceMonitorrouter = APIRouter(prefix="/benchmark", tags=["benchmark"])class BenchmarkRequest(BaseModel):question: str = Field(..., min_length=1)answer: str = Field(..., min_length=1)contexts: List[str] = Field(default_factory=list)reference_answer: Optional[str] = Nonen_generated_questions: int = 3@router.post("/evaluate")def benchmark_evaluate(req: BenchmarkRequest) -> Dict[str, Any]:perf = PerformanceMonitor()perf.start("benchmark_total")perf.start("metrics")result = evaluate_rag_response(question=req.question,answer=req.answer,contexts=req.contexts,reference_answer=req.reference_answer,n_generated_questions=req.n_generated_questions,)perf.stop("metrics")perf.stop("benchmark_total")result["timings_ms"] = perf.report()return result
2 unmodified lines34567891011122 unmodified linesfrom fastapi import APIRouterfrom src.app.api.admin import router as admin_routerfrom src.app.api.chat import router as chat_routerfrom src.app.api.ingest import router as ingest_routerapi_router = APIRouter()api_router.include_router(chat_router)api_router.include_router(ingest_router)api_router.include_router(benchmark_router)2 unmodified lines345678910111213142 unmodified linesfrom fastapi import APIRouterfrom src.app.api.admin import router as admin_routerfrom src.app.api.benchmark import router as benchmark_routerfrom src.app.api.chat import router as chat_routerfrom src.app.api.ingest import router as ingest_routerapi_router = APIRouter()api_router.include_router(admin_router)api_router.include_router(benchmark_router)api_router.include_router(chat_router)api_router.include_router(ingest_router)
189 unmodified lines190191192193194195196197198199128 unmodified lines328329330331189 unmodified linesdoc_title = fp.stemdoc_prefix = _slugify(doc_title)ingestion_output = ingest_document(text=text,document_title=doc_title,)graph = materialize_graph_from_ingestion(ingestion_output)graph = build_hierarchical_summaries(128 unmodified lines"graph_nodes": len(graph.get("nodes", [])),"graph_edges": len(graph.get("edges", [])),"docs": _RUNTIME["graph_doc_count"],}189 unmodified lines190191192193194195196128 unmodified lines325326327328189 unmodified linesdoc_title = fp.stemdoc_prefix = _slugify(doc_title)ingestion_output = ingest_document(text=text)graph = materialize_graph_from_ingestion(ingestion_output)graph = build_hierarchical_summaries(128 unmodified lines"graph_nodes": len(graph.get("nodes", [])),"graph_edges": len(graph.get("edges", [])),"docs": _RUNTIME["graph_doc_count"],}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242from __future__ import annotationsimport mathimport refrom typing import Any, Dict, List, Optionalfrom src.rag.openai_clients import get_embedings, get_llm_TOKEN_RE = re.compile(r"\w+", re.UNICODE)def _norm_space(text: str) -> str:return " ".join((text or "").split()).strip()def _tokens(text: str) -> set[str]:return {t.lower() for t in _TOKEN_RE.findall(_norm_space(text)) if t.strip()}def _split_sentences(text: str) -> List[str]:parts = re.split(r"(?<=[\.!?;])\s+", _norm_space(text))return [p.strip() for p in parts if p.strip()]def _jaccard(a: str, b: str) -> float:ta, tb = _tokens(a), _tokens(b)if not ta or not tb:return 0.0inter = len(ta & tb)union = len(ta | tb)return float(inter) / float(union or 1)def _cosine(a: List[float], b: List[float]) -> float:if not a or not b or len(a) != len(b):return 0.0dot = sum(x * y for x, y in zip(a, b))na = math.sqrt(sum(x * x for x in a))nb = math.sqrt(sum(y * y for y in b))if na == 0 or nb == 0:return 0.0return dot / (na * nb)def split_claims(answer: str) -> List[str]:"""Tách answer thành các claim ngắn để chấm faithfulness."""claims = _split_sentences(answer)return claims or ([_norm_space(answer)] if _norm_space(answer) else [])def score_faithfulness(answer: str,contexts: List[str],*,support_threshold: float = 0.2,) -> Dict[str, Any]:claims = split_claims(answer)context_blob = [c for c in contexts if _norm_space(c)]judged: List[Dict[str, Any]] = []supported = 0for c in claims:best = 0.0best_idx = -1for i, ctx in enumerate(context_blob):s = _jaccard(c, ctx)if s > best:best = sbest_idx = iis_supported = best >= support_thresholdsupported += int(is_supported)judged.append({"claim": c,"supported": is_supported,"best_support_score": round(best, 4),"support_context_index": best_idx,})score = float(supported) / float(len(claims) or 1)return {"score": round(score, 4),"supported_claims": supported,"total_claims": len(claims),"claims": judged,}def _llm_generate_questions_from_answer(answer: str, n: int) -> List[str]:llm = get_llm()prompt = ("Sinh {n} câu hỏi ngắn (tiếng Việt) mà câu trả lời bên dưới có thể trả lời. ""Trả về mỗi câu trên một dòng, không đánh số.\n\n""ANSWER:\n{ans}").format(n=n, ans=answer)resp = llm.invoke(prompt)lines = [_norm_space(re.sub(r"^[\-\d\.)\s]+", "", l))for l in str(getattr(resp, "content", "") or "").splitlines()]lines = [l for l in lines if l]return lines[:n]def _heuristic_generate_questions_from_answer(answer: str, n: int) -> List[str]:sents = _split_sentences(answer)if not sents:return []out: List[str] = []for s in sents[:n]:out.append(f"Nội dung nào được nêu trong câu: '{s}'?")while len(out) < n:out.append("Thông tin chính của câu trả lời là gì?")return out[:n]def generate_questions_from_answer(answer: str, n: int = 3) -> List[str]:try:qs = _llm_generate_questions_from_answer(answer, n)if qs:return qs[:n]except Exception:passreturn _heuristic_generate_questions_from_answer(answer, n)def score_answer_relevancy(question: str,answer: str,*,n_generated_questions: int = 3,) -> Dict[str, Any]:generated = generate_questions_from_answer(answer, n=n_generated_questions)if not generated:return {"score": 0.0,"generated_questions": [],"similarities": [],}sims: List[float] = []try:emb = get_embedings()q_vec = emb.embed_query(question)for gq in generated:gq_vec = emb.embed_query(gq)sims.append(_cosine(q_vec, gq_vec))except Exception:sims = [_jaccard(question, gq) for gq in generated]score = sum(sims) / float(len(sims) or 1)return {"score": round(score, 4),"generated_questions": generated,"similarities": [round(x, 4) for x in sims],}def score_context_precision(question: str, contexts: List[str]) -> Dict[str, Any]:relevance = [1 if _jaccard(question, c) >= 0.08 else 0 for c in contexts]precisions: List[float] = []rel_count = 0for i, rel in enumerate(relevance, start=1):rel_count += relprecisions.append(rel_count / i)weighted = [p for p, rel in zip(precisions, relevance) if rel == 1]if not weighted:return {"score": 0.0,"relevance_labels": relevance,"precision_at_k": [round(x, 4) for x in precisions],}score = sum(weighted) / float(len(weighted))return {"score": round(score, 4),"relevance_labels": relevance,"precision_at_k": [round(x, 4) for x in precisions],}def score_context_recall(reference_answer: str, contexts: List[str]) -> Dict[str, Any]:refs = _split_sentences(reference_answer)if not refs:return {"score": 0.0,"covered_sentences": 0,"total_sentences": 0,}covered = 0detail: List[Dict[str, Any]] = []for sent in refs:best = max((_jaccard(sent, c) for c in contexts), default=0.0)ok = best >= 0.1covered += int(ok)detail.append({"sentence": sent, "covered": ok, "best_overlap": round(best, 4)})score = covered / float(len(refs) or 1)return {"score": round(score, 4),"covered_sentences": covered,"total_sentences": len(refs),"sentences": detail,}def evaluate_rag_response(*,question: str,answer: str,contexts: List[str],reference_answer: Optional[str] = None,n_generated_questions: int = 3,) -> Dict[str, Any]:faithfulness = score_faithfulness(answer, contexts)answer_relevancy = score_answer_relevancy(question,answer,n_generated_questions=n_generated_questions,)context_precision = score_context_precision(question, contexts)context_recall = score_context_recall(reference_answer or answer, contexts)return {"faithfulness": faithfulness,"answer_relevancy": answer_relevancy,"context_precision": context_precision,"context_recall": context_recall,"meta": {"context_count": len(contexts),"uses_reference_answer": bool(reference_answer),"n_generated_questions": n_generated_questions,},}
123456789101112from __future__ import annotationsEXAMPLE_BENCHMARK_REQUEST = {"question": "Mức phạt hành vi bạo lực gia đình là gì?","answer": "Hành vi bạo lực gia đình có thể bị xử phạt hành chính theo quy định.","reference_answer": "Theo quy định, hành vi bạo lực gia đình có thể bị xử phạt hành chính hoặc truy cứu trách nhiệm hình sự tùy mức độ.","contexts": ["Người có hành vi bạo lực gia đình tùy theo mức độ vi phạm mà bị xử phạt vi phạm hành chính hoặc bị truy cứu trách nhiệm hình sự.","Ủy ban nhân dân cấp xã có trách nhiệm tổ chức thực hiện biện pháp phòng, chống bạo lực gia đình.",],"n_generated_questions": 3,}
1234567891011121314151617181920212223242526272829303132333435363738394041from __future__ import annotationsimport timefrom dataclasses import dataclass, fieldfrom typing import Any, Dict@dataclassclass PerfStep:name: strstarted_at: floatended_at: float | None = None@propertydef elapsed_ms(self) -> float:end = self.ended_at if self.ended_at is not None else time.perf_counter()return round((end - self.started_at) * 1000, 3)@dataclassclass PerformanceMonitor:steps: Dict[str, PerfStep] = field(default_factory=dict)def start(self, name: str) -> None:self.steps[name] = PerfStep(name=name, started_at=time.perf_counter())def stop(self, name: str) -> None:step = self.steps.get(name)if step is None:self.steps[name] = PerfStep(name=name, started_at=time.perf_counter(), ended_at=time.perf_counter())returnstep.ended_at = time.perf_counter()def report(self) -> Dict[str, Any]:return {k: {"elapsed_ms": v.elapsed_ms,"done": v.ended_at is not None,}for k, v in self.steps.items()}
47 unmodified lines48495047 unmodified lines"replacement",}_SUMMARY_CACHE: Dict[str, str] = {}47 unmodified lines48495051525354555657585960616263646566676869707172737475767747 unmodified lines"replacement",}_SUMMARY_CACHE: Dict[str, str] = {}def build_hierarchical_summaries(graph: Dict[str, Any],document_title: Optional[str] = None,*,include_clause: bool = False,include_article: bool = True,include_change: bool = True,include_community: bool = False,) -> Dict[str, Any]:"""Fallback no-op builder để giữ compatibility cho runtime.Hiện tại trả lại graph gốc; các summary node đã có thể được tạo từ ingestion."""_ = (document_title,include_clause,include_article,include_change,include_community,)return {"graph": graph,"summary_nodes": [],"summary_edges": [],}
1 unmodified line2345678910111213640 unmodified lines6546556566571 unmodified lineimport jsonimport refrom typing import Any, Dict, List, Optional, Tuplefrom langchain_core.messages import HumanMessage, SystemMessagefrom src.rag.chunking_legal import LegalNode, build_chunks, parse_legal_textfrom src.rag.openai_clients import get_llm# ============================================================# LLM PROMPTS640 unmodified lines"entities": all_entities,"relations": all_relations,"graph_edges": graph_edges,}1 unmodified line2345678910111213141516640 unmodified lines6576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127131 unmodified lineimport jsonimport reimport uuidfrom typing import Any, Dict, List, Optional, Tuplefrom langchain_core.messages import HumanMessage, SystemMessagefrom qdrant_client.http import models as qmfrom src.rag.chunking_legal import LegalNode, build_chunks, parse_legal_textfrom src.rag.openai_clients import get_llmfrom src.storage.qdrant_store import get_qdrant_client, upsert_points# ============================================================# LLM PROMPTS640 unmodified lines"entities": all_entities,"relations": all_relations,"graph_edges": graph_edges,}def upsert_chunks(chunks: List[Dict[str, Any]],*,embeddings: Any,meta: Optional[Dict[str, Any]] = None,) -> int:"""Embed và upsert các chunk vào Qdrant.- chunks: [{"text": "...", "metadata": {...}}, ...]- meta: metadata mặc định ở mức document, merge vào metadata chunk."""if not chunks:return 0points: List[qm.PointStruct] = []base_meta = dict(meta or {})for idx, chunk in enumerate(chunks):text = _norm_space(str(chunk.get("text") or ""))if not text:continuechunk_meta = dict(chunk.get("metadata") or {})merged_meta = {**base_meta, **chunk_meta}chunk_id = str(merged_meta.get("chunk_id") or merged_meta.get("node_id") or f"chunk_{idx}")merged_meta["chunk_id"] = chunk_idpoint_id = str(uuid.uuid5(uuid.NAMESPACE_URL, chunk_id))vector = embeddings.embed_query(text)payload = {"text": text,"metadata": merged_meta,**merged_meta,}points.append(qm.PointStruct(id=point_id,vector=vector,payload=payload,))if not points:return 0client = get_qdrant_client()upsert_points(client, points)return len(points)
7 unmodified lines891011121314161 unmodified lines17617717817918018145 unmodified lines22722822923023123223319 unmodified lines253254255256257258272 unmodified lines5315325335347 unmodified linesfrom src.rag.bm25_corpus import load_bm25_statsfrom src.rag.hybrid import hybrid_rankfrom src.rag.legal_versioning import annotate_graph_with_versioningfrom src.rag.openai_clients import get_embedingsfrom src.rag.rerank_cross import cross_rerankfrom src.storage.qdrant_store import get_qdrant_client, search_qdrant161 unmodified linesreturn embeddings.embed_query(question)def _extract_node_id_from_payload(payload: Dict[str, Any]) -> Optional[str]:if not payload:return None45 unmodified linesif filters:merged_filters.update({k: v for k, v in filters.items() if v is not None and v != ""})query_vector = _embed_query(question)client = get_qdrant_client()raw_points = search_qdrant(19 unmodified linesfor rank_score, cand in ranked:item = dict(cand)item["hybrid_score"] = float(rank_score)out.append(item)return out272 unmodified lines"seed_candidates": seeds,"graph_scores": graph_scores,"passages": passages,}7 unmodified lines891011121314161 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221345 unmodified lines25926026126226326426526626726826927027127227327419 unmodified lines294295296297298299300272 unmodified lines5735745755767 unmodified linesfrom src.rag.bm25_corpus import load_bm25_statsfrom src.rag.hybrid import hybrid_rankfrom src.rag.legal_versioning import annotate_graph_with_versioningfrom src.rag.openai_clients import get_embedings, get_llmfrom src.rag.rerank_cross import cross_rerankfrom src.storage.qdrant_store import get_qdrant_client, search_qdrant161 unmodified linesreturn embeddings.embed_query(question)def generate_query_variants(question: str, *, n: int = 3) -> List[str]:"""Sinh thêm các biến thể của câu hỏi người dùng trước khi tính similarity.Fallback về câu hỏi gốc nếu LLM fail."""q = (question or "").strip()if not q:return []try:llm = get_llm()prompt = (f"Sinh {n} câu hỏi biến thể tiếng Việt có cùng ý nghĩa pháp lý với câu hỏi sau. ""Mỗi câu 1 dòng, không đánh số, không giải thích.\n\n"f"QUESTION: {q}")response = llm.invoke(prompt)lines = [str(x).strip(" -\t") for x in str(getattr(response, "content", "") or "").splitlines()]variants = [x for x in lines if x]except Exception:variants = []merged = [q]for v in variants:if v.lower() not in {x.lower() for x in merged}:merged.append(v)if len(merged) >= n + 1:breakreturn mergeddef _extract_node_id_from_payload(payload: Dict[str, Any]) -> Optional[str]:if not payload:return None45 unmodified linesif filters:merged_filters.update({k: v for k, v in filters.items() if v is not None and v != ""})expanded_questions = generate_query_variants(question, n=3)embeddings = get_embedings()vectors = [embeddings.embed_query(q) for q in expanded_questions] or [embeddings.embed_query(question)]dims = len(vectors[0]) if vectors and vectors[0] else 0query_vector = [0.0] * dimsfor vec in vectors:for i, v in enumerate(vec):query_vector[i] += float(v)query_vector = [v / float(len(vectors)) for v in query_vector]client = get_qdrant_client()raw_points = search_qdrant(19 unmodified linesfor rank_score, cand in ranked:item = dict(cand)item["hybrid_score"] = float(rank_score)item["query_variants"] = expanded_questionsout.append(item)return out272 unmodified lines"seed_candidates": seeds,"graph_scores": graph_scores,"passages": passages,}
scripts/ingest.py+10-1
src/app/api/benchmark.py+41
src/app/api/router.py+3-1
src/app/runtime.py+2-5
src/eval/benchmark_metrics.py+242
src/eval/examples.py+12
src/eval/performance_monitor.py+41
src/rag/hierachical_summary.py+27
src/rag/ingestion.py+57-1
src/rag/retrieval_pipeline.py+45-3