anky2002 commited on
Commit
3168ac9
·
verified ·
1 Parent(s): 2b7f13d

Upload agents/utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. agents/utils.py +105 -0
agents/utils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FORENSIQ — Shared utilities for all agents."""
2
+
3
+ import numpy as np
4
+ from typing import List, Dict, Any
5
+
6
+
7
+ def compute_agent_confidence(scores: List[float]) -> float:
8
+ """
9
+ Compute agent confidence using agreement-vs-cancellation logic.
10
+ Backported from semantic agent to ALL signal agents.
11
+
12
+ Returns a confidence value between 0.1 and 1.0 that reflects:
13
+ - High confidence when scores agree in direction and have high magnitude
14
+ - Low confidence when scores cancel each other out
15
+ - Low confidence when all scores are near zero (no signal)
16
+ """
17
+ if not scores:
18
+ return 0.1
19
+
20
+ avg = float(np.mean(scores))
21
+
22
+ # Classify each score's direction
23
+ signs = [1 if s > 0.05 else (-1 if s < -0.05 else 0) for s in scores]
24
+ n_pos = sum(1 for s in signs if s > 0)
25
+ n_neg = sum(1 for s in signs if s < 0)
26
+ n_neu = sum(1 for s in signs if s == 0)
27
+
28
+ if n_pos > 0 and n_neg > 0:
29
+ # Scores cancel — low confidence
30
+ agreement = max(n_pos, n_neg) / (n_pos + n_neg)
31
+ return min(1.0, 0.15 + 0.5 * abs(avg) * agreement)
32
+ elif n_neu == len(signs):
33
+ # All genuinely neutral — low confidence
34
+ return 0.2
35
+ else:
36
+ # Scores agree — confidence scales with magnitude
37
+ return min(1.0, 0.3 + 0.6 * abs(avg))
38
+
39
+
40
+ def compute_failure_prob(n_ran: int, n_total: int, n_insufficient: int = 0) -> float:
41
+ """
42
+ Compute agent failure probability.
43
+ Accounts for both crashed tests AND tests returning insufficient data.
44
+
45
+ n_ran: tests that returned a score (including insufficient-data ones)
46
+ n_total: total tests attempted
47
+ n_insufficient: tests that returned score=0 due to insufficient data
48
+ """
49
+ n_effective = n_ran - n_insufficient # tests that actually produced signal
50
+ return max(0.0, 1.0 - n_effective / max(n_total, 1))
51
+
52
+
53
+ def run_agent_tests(tests, img, agent_name):
54
+ """
55
+ Shared test runner for all signal-processing agents.
56
+ Handles: running tests, tagging insufficient-data, computing confidence properly.
57
+ """
58
+ findings, scores = [], []
59
+ n_insufficient = 0
60
+
61
+ for fn in tests:
62
+ try:
63
+ r = fn(img)
64
+ findings.append(r)
65
+
66
+ sc = r.get("score", 0)
67
+ note = r.get("note", "")
68
+
69
+ # P7: Detect insufficient-data results — tag as not_applicable
70
+ is_insufficient = (sc == 0.0 and any(kw in note.lower() for kw in
71
+ ["insufficient", "too small", "no data", "not available", "few ", "no "]))
72
+
73
+ if is_insufficient:
74
+ r["not_applicable"] = True
75
+ n_insufficient += 1
76
+
77
+ scores.append(sc)
78
+ except Exception as e:
79
+ findings.append({"test": fn.__name__, "error": str(e), "score": 0})
80
+
81
+ # Filter out not_applicable scores for averaging
82
+ active_scores = [s for s, f in zip(scores, findings)
83
+ if not f.get("not_applicable", False)]
84
+
85
+ avg = float(np.mean(active_scores)) if active_scores else 0.0
86
+ conf = compute_agent_confidence(active_scores)
87
+ fail = compute_failure_prob(len(scores), len(tests), n_insufficient)
88
+
89
+ # Build rationale
90
+ viol = [f["test"] for f in findings if f.get("score", 0) > 0.2 and not f.get("not_applicable")]
91
+ comp = [f["test"] for f in findings if f.get("score", 0) < -0.1 and not f.get("not_applicable")]
92
+
93
+ domain = agent_name.replace(" Agent", "")
94
+ if viol:
95
+ rat = f"{domain} violations: {', '.join(viol)}."
96
+ elif comp:
97
+ rat = f"{domain} consistent: {', '.join(comp)}."
98
+ else:
99
+ rat = f"{domain} inconclusive."
100
+
101
+ for f in findings:
102
+ if f.get("note") and not f.get("not_applicable"):
103
+ rat += f" [{f['test']}]: {f['note']}."
104
+
105
+ return findings, avg, conf, fail, rat