File size: 10,956 Bytes
b7d0804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
from pathlib import Path

# Remove BOM from Python files
for path in Path("app").rglob("*.py"):
    text = path.read_text(encoding="utf-8-sig")
    text = text.replace("\ufeff", "")
    path.write_text(text, encoding="utf-8")

print("BOM cleanup completed.")


# =====================================================
# 1. Create GraphRAG fusion evaluator
# =====================================================

Path("app/evaluation/graph_fusion_evaluator.py").write_text(r'''
import re
from typing import Dict, Any, List, Optional

from app.retrieval.hybrid_search_service import retrieve_chunks
from app.retrieval.reranking_service import rerank_results
from app.retrieval.citation_service import attach_source_ids
from app.generation.context_cleaner import clean_retrieved_results
from app.graph.graph_guided_retriever import graph_guided_retrieve
from app.graph.graph_retrieval_fusion import fuse_retrieval_results_with_graph

try:
    from app.graph.graph_quality import (
        is_low_quality_chunk_text,
        is_meta_showcase_chunk_text,
        is_cover_or_marketing_chunk_text
    )
except Exception:
    def is_low_quality_chunk_text(text: str) -> bool:
        return False

    def is_meta_showcase_chunk_text(text: str) -> bool:
        return False

    def is_cover_or_marketing_chunk_text(text: str) -> bool:
        return False


def get_value(obj, key: str, default=None):
    if isinstance(obj, dict):
        return obj.get(key, default)

    return getattr(obj, key, default)


def tokenize(text: str) -> List[str]:
    return re.findall(r"[a-zA-Z0-9_]+", str(text or "").lower())


def get_content(result: Any) -> str:
    return (
        get_value(result, "content")
        or get_value(result, "text")
        or get_value(result, "raw_content")
        or ""
    )


def get_chunk_id(result: Any) -> str:
    return str(
        get_value(result, "chunk_id")
        or get_value(result, "id")
        or ""
    )


def preview(text: str, max_chars: int = 350) -> str:
    text = str(text or "").replace("\n", " ").strip()

    if len(text) > max_chars:
        return text[:max_chars] + "..."

    return text


def query_terms(query: str) -> List[str]:
    stopwords = {
        "what", "is", "are", "the", "a", "an", "of", "to", "and",
        "or", "why", "how", "does", "do", "explain", "define"
    }

    return [
        term for term in tokenize(query)
        if term not in stopwords and len(term) > 1
    ]


def quality_score_for_result(query: str, result: Any) -> Dict[str, Any]:
    content = get_content(result)
    lower = content.lower()
    tokens = set(tokenize(content))
    terms = query_terms(query)

    score = 0.0
    reasons = []

    for term in terms:
        if term in tokens:
            score += 2.0
            reasons.append(f"contains query term: {term}")
        elif len(term) >= 4 and term in lower:
            score += 1.0
            reasons.append(f"contains query substring: {term}")

    if "rag" in terms:
        definition_markers = [
            "rag is",
            "rag stands for",
            "retrieval-augmented generation",
            "retrieval augmented generation",
            "adds a retrieval step",
            "before generation",
            "document corpus",
            "reduces hallucination"
        ]

        for marker in definition_markers:
            if marker in lower:
                score += 3.0
                reasons.append(f"definition marker: {marker}")

    if get_value(result, "graph_supported", False):
        score += 1.5
        reasons.append("supported by graph and retrieval")

    retrieval_source = get_value(result, "retrieval_source")

    if retrieval_source == "graph":
        score += 0.5
        reasons.append("selected by graph retrieval")

    penalties = []

    if is_low_quality_chunk_text(content):
        score -= 5.0
        penalties.append("low quality / TOC-like chunk")

    if is_meta_showcase_chunk_text(content):
        score -= 5.0
        penalties.append("meta / LinkedIn / resume-style chunk")

    if is_cover_or_marketing_chunk_text(content):
        score -= 5.0
        penalties.append("cover / marketing chunk")

    score = round(score, 4)

    return {
        "quality_score": score,
        "positive_reasons": reasons,
        "penalties": penalties
    }


def summarize_results(query: str, results: List[Any], label: str) -> Dict[str, Any]:
    rows = []

    for rank, result in enumerate(results, start=1):
        quality = quality_score_for_result(query, result)

        rows.append(
            {
                "rank": rank,
                "chunk_id": get_chunk_id(result),
                "page_number": get_value(result, "page_number"),
                "source_file_name": get_value(result, "source_file_name"),
                "retrieval_source": get_value(result, "retrieval_source"),
                "graph_supported": get_value(result, "graph_supported", False),
                "score": get_value(result, "score"),
                "graph_score": get_value(result, "graph_score"),
                "quality_score": quality["quality_score"],
                "positive_reasons": quality["positive_reasons"],
                "penalties": quality["penalties"],
                "content_preview": preview(get_content(result))
            }
        )

    avg_quality = 0.0

    if rows:
        avg_quality = round(
            sum(row["quality_score"] for row in rows) / len(rows),
            4
        )

    noisy_count = sum(1 for row in rows if row["penalties"])

    return {
        "label": label,
        "count": len(rows),
        "average_quality_score": avg_quality,
        "noisy_chunk_count": noisy_count,
        "results": rows
    }


def compare_graph_fusion_retrieval(
    document_id: str,
    query: str,
    top_k: int = 5,
    retrieval_mode: str = "hybrid",
    use_reranker: bool = True,
    graph_entity_limit: int = 8,
    graph_retrieval_top_k: int = 5
) -> Dict[str, Any]:

    retrieval_output = retrieve_chunks(
        query=query,
        document_id=document_id,
        top_k=top_k,
        retrieval_mode=retrieval_mode
    )

    normal_results = retrieval_output.get("results", [])

    if use_reranker:
        normal_results = rerank_results(
            query=query,
            results=normal_results,
            top_k=top_k
        )
    else:
        normal_results = normal_results[:top_k]

    cleaned_normal_results = clean_retrieved_results(normal_results)
    sourced_normal_results = attach_source_ids(cleaned_normal_results)

    graph_result = graph_guided_retrieve(
        document_id=document_id,
        query=query,
        graph_entity_limit=graph_entity_limit,
        top_k=graph_retrieval_top_k
    )

    fusion_result = fuse_retrieval_results_with_graph(
        document_id=document_id,
        query=query,
        retrieval_results=sourced_normal_results,
        graph_entity_limit=graph_entity_limit,
        graph_top_k=graph_retrieval_top_k,
        final_top_k=max(top_k, graph_retrieval_top_k)
    )

    fused_results = fusion_result.get("fused_results", [])

    normal_summary = summarize_results(
        query=query,
        results=sourced_normal_results,
        label="normal_retrieval"
    )

    graph_summary = summarize_results(
        query=query,
        results=graph_result.get("results", []),
        label="graph_guided_retrieval"
    )

    fused_summary = summarize_results(
        query=query,
        results=fused_results,
        label="fused_retrieval"
    )

    improvement = round(
        fused_summary["average_quality_score"]
        - normal_summary["average_quality_score"],
        4
    )

    if improvement > 0:
        verdict = "fusion_improved_retrieval_quality"
    elif improvement == 0:
        verdict = "fusion_quality_same_as_normal_retrieval"
    else:
        verdict = "fusion_may_be_adding_noise"

    return {
        "status": "success",
        "document_id": document_id,
        "query": query,
        "retrieval_mode": retrieval_mode,
        "use_reranker": use_reranker,
        "comparison": {
            "normal_average_quality": normal_summary["average_quality_score"],
            "graph_average_quality": graph_summary["average_quality_score"],
            "fused_average_quality": fused_summary["average_quality_score"],
            "fusion_quality_delta": improvement,
            "verdict": verdict
        },
        "fusion_stats": {
            "fusion_used": fusion_result.get("fusion_used", False),
            "normal_count": fusion_result.get("normal_count"),
            "graph_added_count": fusion_result.get("graph_added_count"),
            "graph_supported_count": fusion_result.get("graph_supported_count"),
            "final_count": fusion_result.get("final_count"),
            "reason": fusion_result.get("reason")
        },
        "normal_retrieval": normal_summary,
        "graph_guided_retrieval": graph_summary,
        "fused_retrieval": fused_summary,
        "notes": [
            "This is a heuristic debug evaluator, not a benchmark metric.",
            "Use it to inspect whether graph retrieval is adding useful evidence or noisy chunks.",
            "For formal evaluation, use labeled questions and relevance judgments."
        ]
    }
''', encoding="utf-8")


# =====================================================
# 2. Patch main.py
# =====================================================

main_path = Path("app/main.py")
text = main_path.read_text(encoding="utf-8-sig")
text = text.replace("\ufeff", "")

if "from app.evaluation.graph_fusion_evaluator import compare_graph_fusion_retrieval" not in text:
    text = "from app.evaluation.graph_fusion_evaluator import compare_graph_fusion_retrieval\n" + text

old_phases = [
    "Phase 18 - Graph Quality Cleanup",
    "Phase 17 - Graph Vector Retrieval Fusion",
    "Phase 16 - Graph-Guided Retrieval Debug Layer"
]

for old in old_phases:
    text = text.replace(old, "Phase 19 - GraphRAG Retrieval Fusion Evaluation")

if "# GraphRAG fusion evaluation endpoint" not in text:
    text += '''

# GraphRAG fusion evaluation endpoint

@app.get("/documents/{document_id}/evaluation/graph-fusion")
def evaluate_graph_fusion_for_document(
    document_id: str,
    query: str = Query(..., min_length=1),
    top_k: int = Query(5, ge=1, le=20),
    retrieval_mode: str = Query("hybrid"),
    use_reranker: bool = True,
    graph_entity_limit: int = Query(8, ge=1, le=30),
    graph_retrieval_top_k: int = Query(5, ge=1, le=20)
):
    return compare_graph_fusion_retrieval(
        document_id=document_id,
        query=query,
        top_k=top_k,
        retrieval_mode=retrieval_mode,
        use_reranker=use_reranker,
        graph_entity_limit=graph_entity_limit,
        graph_retrieval_top_k=graph_retrieval_top_k
    )
'''

main_path.write_text(text, encoding="utf-8")

print("Phase 19 GraphRAG retrieval fusion evaluation added.")