Sdm0 commited on
Commit
784e5ea
·
verified ·
1 Parent(s): 5f5f7be

Deploy 63ed7874

Browse files
Files changed (1) hide show
  1. app.py +126 -9
app.py CHANGED
@@ -162,7 +162,54 @@ def _build_and_stream(repo: str, pr_number: int) -> tuple:
162
  handler=handler,
163
  )
164
 
165
- return state, config, cost_tracker.summary()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
 
168
  def _format_findings_table(findings: list) -> str:
@@ -232,6 +279,72 @@ def _format_verdict(verdict: Verdict | None) -> str:
232
  )
233
 
234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  def _format_findings_count(findings: list) -> str:
236
  """Build a compact summary count per severity."""
237
  counts: dict[str, int] = {}
@@ -277,7 +390,7 @@ def _get_deploy_info() -> tuple[str, str]:
277
  def run_review(repo: str, pr_number: int, progress=gr.Progress()):
278
  """Run the review pipeline up to human-in-the-loop interrupt."""
279
  if not repo or "/" not in repo:
280
- yield [None, None, None, None], "❌ Enter a repo in `owner/name` format."
281
  return
282
 
283
  _cleanup_db()
@@ -285,7 +398,7 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
285
  progress(0.1, desc="Building graph…")
286
 
287
  try:
288
- state, config, cost_summary = _build_and_stream(repo.strip(), pr_number)
289
  except Exception as exc:
290
  log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
291
  yield [
@@ -293,7 +406,7 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
293
  gr.update(visible=False),
294
  gr.update(visible=True),
295
  gr.update(visible=True, value=f"❌ Review failed: {exc}"),
296
- None, None, None, None,
297
  gr.update(visible=False),
298
  ]
299
  return
@@ -302,7 +415,7 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
302
  values = state.values
303
 
304
  if not tasks:
305
- yield [None, None, None, None], "ℹ️ Review completed without findings."
306
  return
307
 
308
  verdict: Verdict | None = values.get("verdict")
@@ -311,6 +424,7 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
311
  progress(0.8, desc="Formatting results…")
312
 
313
  verdict_html = _format_verdict(verdict)
 
314
  findings_html = _format_findings_table(findings)
315
  count_html = _format_findings_count(findings)
316
  # Append cost info to count display
@@ -321,7 +435,7 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
321
  )
322
 
323
  yield (
324
- [verdict_html, findings_html, count_html, config_json],
325
  None,
326
  )
327
 
@@ -608,6 +722,7 @@ with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
608
  verdict_display = gr.HTML()
609
  count_display = gr.HTML()
610
  findings_display = gr.HTML()
 
611
 
612
  with gr.Row():
613
  approve_btn = gr.Button("✅ Approve & Post", variant="primary")
@@ -624,7 +739,7 @@ with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
624
  gr.update(visible=True, variant="stop"),
625
  gr.update(visible=False),
626
  gr.update(visible=False, value=""),
627
- *[None, None, None, None],
628
  gr.update(visible=False),
629
  ]
630
 
@@ -635,11 +750,11 @@ with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
635
  gr.update(visible=False),
636
  gr.update(visible=True),
637
  gr.update(visible=True, value=err),
638
- *[None, None, None, None],
639
  gr.update(visible=False),
640
  ]
641
  else:
642
- verdict_html, findings_html, count_html, config_json = result
643
  yield [
644
  gr.update(visible=False),
645
  gr.update(visible=False),
@@ -648,6 +763,7 @@ with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
648
  gr.update(value=verdict_html),
649
  gr.update(value=count_html),
650
  gr.update(value=findings_html),
 
651
  config_json,
652
  gr.update(visible=True),
653
  ]
@@ -663,6 +779,7 @@ with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
663
  verdict_display,
664
  count_display,
665
  findings_display,
 
666
  pr_state,
667
  results_panel,
668
  ],
 
162
  handler=handler,
163
  )
164
 
165
+ # ── Compute and log RAGAS retrieval scores ─────────────────
166
+ ragas_scores: dict[str, float] = {}
167
+ context_chunks = state.values.get("context_chunks", [])
168
+ if context_chunks:
169
+ try:
170
+ from eval_data.ragas_eval import compute_ragas_retrieval_scores
171
+
172
+ query = state.values.get("diff", "") or ""
173
+ contexts = [c.content for c in context_chunks if c.content]
174
+
175
+ # Build answer text from findings + verdict for
176
+ # faithfulness & answer_relevancy metrics
177
+ answer_lines = []
178
+ for f in findings:
179
+ answer_lines.append(
180
+ f"[{f.severity.value}] {f.file_path}:{f.line_start}-{f.line_end}: {f.comment}"
181
+ )
182
+ if state.values.get("verdict"):
183
+ v = state.values["verdict"]
184
+ answer_lines.append(
185
+ f"Verdict: {v.recommendation} (score={v.overall_score}/10) — {v.summary}"
186
+ )
187
+ answer_text = "\n".join(answer_lines) if answer_lines else None
188
+
189
+ ragas_scores = compute_ragas_retrieval_scores(
190
+ query=query,
191
+ retrieved_contexts=contexts,
192
+ answer=answer_text,
193
+ )
194
+
195
+ for metric_name, value in ragas_scores.items():
196
+ log_langfuse_score(
197
+ name=f"ragas_{metric_name}",
198
+ value=value,
199
+ comment=f"{repo}#{pr_number} — {metric_name}",
200
+ handler=handler,
201
+ )
202
+
203
+ logger.info(
204
+ "RAGAS scores logged to Langfuse: %s",
205
+ " | ".join(f"{k}={v:.4f}" for k, v in ragas_scores.items()),
206
+ )
207
+ except ImportError:
208
+ logger.info("RAGAS not installed — skipping RAGAS scoring (pip install ragas)")
209
+ except Exception as exc:
210
+ logger.warning("RAGAS scoring failed: %s", exc)
211
+
212
+ return state, config, cost_tracker.summary(), ragas_scores
213
 
214
 
215
  def _format_findings_table(findings: list) -> str:
 
279
  )
280
 
281
 
282
+ RAGAS_METRIC_LABELS = {
283
+ "context_precision": "Context Precision",
284
+ "context_recall": "Context Recall",
285
+ "faithfulness": "Faithfulness",
286
+ "answer_relevancy": "Answer Relevancy",
287
+ "mmr": "Mean Reciprocal Rank",
288
+ }
289
+
290
+ RAGAS_METRIC_TOOLTIPS = {
291
+ "context_precision": "Are the most relevant code chunks ranked first?",
292
+ "context_recall": "Did we find ALL the relevant code? (requires ground truth)",
293
+ "faithfulness": "Does the review answer stick to the retrieved code?",
294
+ "answer_relevancy": "Does the review address the PR diff?",
295
+ "mmr": "How early in the list does the first useful chunk appear?",
296
+ }
297
+
298
+
299
+ def _format_ragas_scores(scores: dict[str, float]) -> str:
300
+ """Build an HTML card showing RAGAS retrieval quality metrics."""
301
+ if not scores:
302
+ return ""
303
+
304
+ def _score_color(val: float) -> str:
305
+ if val >= 0.8:
306
+ return "#16a34a"
307
+ elif val >= 0.5:
308
+ return "#ca8a04"
309
+ else:
310
+ return "#dc2626"
311
+
312
+ bars: list[str] = []
313
+ for key, value in scores.items():
314
+ label = RAGAS_METRIC_LABELS.get(key, key.replace("_", " ").title())
315
+ tooltip = RAGAS_METRIC_TOOLTIPS.get(key, "")
316
+ color = _score_color(value)
317
+ pct = int(value * 100)
318
+ bars.append(
319
+ f'<div style="margin-bottom:12px">'
320
+ f'<div style="display:flex;justify-content:space-between;margin-bottom:4px">'
321
+ f'<span style="font-weight:500;color:var(--text-secondary)">'
322
+ f'{label}'
323
+ + (f'<span style="margin-left:4px;cursor:help;font-size:0.85em" '
324
+ f'title="{tooltip}">ℹ️</span>' if tooltip else '')
325
+ + f'</span>'
326
+ f'<span style="font-weight:700;color:{color}">{value:.3f}</span>'
327
+ f'</div>'
328
+ f'<div style="height:8px;background:var(--spinner-track);border-radius:4px;overflow:hidden">'
329
+ f'<div style="height:100%;width:{pct}%;background:{color};'
330
+ f'border-radius:4px;transition:width 0.6s ease"></div>'
331
+ f'</div>'
332
+ f'</div>'
333
+ )
334
+
335
+ return (
336
+ f'<div style="border:1px solid var(--border-color);border-radius:12px;'
337
+ f'padding:16px 20px;margin-top:12px;background:var(--bg-card)">'
338
+ f'<div style="display:flex;align-items:center;gap:8px;margin-bottom:16px">'
339
+ f'<span style="font-size:1.1em">📊</span>'
340
+ f'<span style="font-weight:600;color:var(--text-primary)">'
341
+ f'Retrieval Quality (RAGAS)</span>'
342
+ f'</div>'
343
+ + "".join(bars)
344
+ + f'</div>'
345
+ )
346
+
347
+
348
  def _format_findings_count(findings: list) -> str:
349
  """Build a compact summary count per severity."""
350
  counts: dict[str, int] = {}
 
390
  def run_review(repo: str, pr_number: int, progress=gr.Progress()):
391
  """Run the review pipeline up to human-in-the-loop interrupt."""
392
  if not repo or "/" not in repo:
393
+ yield [None, None, None, None, None], "❌ Enter a repo in `owner/name` format."
394
  return
395
 
396
  _cleanup_db()
 
398
  progress(0.1, desc="Building graph…")
399
 
400
  try:
401
+ state, config, cost_summary, ragas_scores = _build_and_stream(repo.strip(), pr_number)
402
  except Exception as exc:
403
  log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
404
  yield [
 
406
  gr.update(visible=False),
407
  gr.update(visible=True),
408
  gr.update(visible=True, value=f"❌ Review failed: {exc}"),
409
+ None, None, None, None, None,
410
  gr.update(visible=False),
411
  ]
412
  return
 
415
  values = state.values
416
 
417
  if not tasks:
418
+ yield [None, None, None, None, None], "ℹ️ Review completed without findings."
419
  return
420
 
421
  verdict: Verdict | None = values.get("verdict")
 
424
  progress(0.8, desc="Formatting results…")
425
 
426
  verdict_html = _format_verdict(verdict)
427
+ ragas_html = _format_ragas_scores(ragas_scores)
428
  findings_html = _format_findings_table(findings)
429
  count_html = _format_findings_count(findings)
430
  # Append cost info to count display
 
435
  )
436
 
437
  yield (
438
+ [verdict_html, findings_html, count_html, ragas_html, config_json],
439
  None,
440
  )
441
 
 
722
  verdict_display = gr.HTML()
723
  count_display = gr.HTML()
724
  findings_display = gr.HTML()
725
+ ragas_display = gr.HTML()
726
 
727
  with gr.Row():
728
  approve_btn = gr.Button("✅ Approve & Post", variant="primary")
 
739
  gr.update(visible=True, variant="stop"),
740
  gr.update(visible=False),
741
  gr.update(visible=False, value=""),
742
+ *[None, None, None, None, None],
743
  gr.update(visible=False),
744
  ]
745
 
 
750
  gr.update(visible=False),
751
  gr.update(visible=True),
752
  gr.update(visible=True, value=err),
753
+ *[None, None, None, None, None],
754
  gr.update(visible=False),
755
  ]
756
  else:
757
+ verdict_html, findings_html, count_html, ragas_html, config_json = result
758
  yield [
759
  gr.update(visible=False),
760
  gr.update(visible=False),
 
763
  gr.update(value=verdict_html),
764
  gr.update(value=count_html),
765
  gr.update(value=findings_html),
766
+ gr.update(value=ragas_html),
767
  config_json,
768
  gr.update(visible=True),
769
  ]
 
779
  verdict_display,
780
  count_display,
781
  findings_display,
782
+ ragas_display,
783
  pr_state,
784
  results_panel,
785
  ],