File size: 3,279 Bytes
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5900753
7ca0188
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Build serializable, source-labelled FAISS grounding context."""

from __future__ import annotations
from typing import Any
from src.rag.router import ROUTE_FALLBACK, ROUTE_IMAGE, ROUTE_MULTIMODAL


class ContextBuilder:
    def select_best_record(self, faiss_results: list[dict[str, Any]] | None,
                           image_result: dict[str, Any] | None = None) -> dict[str, Any] | None:
        if faiss_results:
            return dict(faiss_results[0])
        if image_result and image_result.get("success") and image_result.get("suggested_record_ids"):
            return {"record_id": image_result["suggested_record_ids"][0], "name": image_result.get("predicted_label", ""), "category": image_result.get("predicted_category", ""), "score": float(image_result.get("confidence", 0.0))}
        return None

    def calculate_final_confidence(self, intent_confidence: float,
                                   retrieval_score: float | None = None,
                                   image_confidence: float | None = None,
                                   route: str | None = None) -> float:
        intent, retrieval, image = float(intent_confidence or 0), float(retrieval_score or 0), float(image_confidence or 0)
        if route == ROUTE_FALLBACK:
            value = 0.0
        elif route in {ROUTE_IMAGE, ROUTE_MULTIMODAL}:
            value = 0.35 * intent + 0.35 * retrieval + 0.30 * image
        else:
            value = 0.40 * intent + 0.60 * retrieval
        return round(max(0.0, min(1.0, value)), 6)

    @staticmethod
    def _grounding_text(record: dict[str, Any]) -> str:
        keys = ("name", "short_description", "terminal", "level", "zone", "direction_text", "accessibility_info", "contact_or_assistance", "text")
        return " | ".join(str(record[key]) for key in keys if record.get(key))

    def build_context(self, query: str, intent: str | None,
                      entities: dict[str, Any] | None, route: str,
                      faiss_results: list[dict[str, Any]] | None = None,
                      image_result: dict[str, Any] | None = None,
                      intent_confidence: float = 0.0) -> dict[str, Any]:
        semantic = list(faiss_results or [])
        selected = self.select_best_record(semantic, image_result)
        record_context = dict(selected or {})
        retrieval_score = float((selected or {}).get("combined_score", (selected or {}).get("score", 0.0)))
        image_confidence = float((image_result or {}).get("confidence", 0.0))
        final = self.calculate_final_confidence(intent_confidence, retrieval_score, image_confidence, route)
        return {
            "query": query, "intent": intent or "", "entities": dict(entities or {}),
            "route": route, "selected_record": selected, "record_context": record_context,
            "semantic_context": semantic, "image_context": dict(image_result or {}),
            "grounding_text": self._grounding_text(record_context),
            "confidence_components": {"intent_confidence": float(intent_confidence), "retrieval_score": retrieval_score, "image_confidence": image_confidence, "final_confidence": final},
            "sources": {"faiss": bool(semantic), "image": bool(image_result and image_result.get("success"))},
        }