Upload agents/statistical_agent.py with huggingface_hub
Browse files- agents/statistical_agent.py +301 -355
agents/statistical_agent.py
CHANGED
|
@@ -1,362 +1,308 @@
|
|
| 1 |
-
"""
|
| 2 |
-
FORENSIQ β Statistical Priors Agent
|
| 3 |
-
Tests natural image statistics violations:
|
| 4 |
-
- DCT coefficient distribution (Laplacian vs Gaussian)
|
| 5 |
-
- Benford's law on first digits of DCT coefficients
|
| 6 |
-
- Gradient sparsity (kurtosis > 3 for natural images)
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
import numpy as np
|
| 10 |
from PIL import Image
|
| 11 |
from scipy.fftpack import dct
|
| 12 |
-
from scipy.stats import kurtosis as
|
| 13 |
-
from scipy.ndimage import gaussian_filter
|
| 14 |
from typing import Dict, Any
|
| 15 |
-
|
| 16 |
from agents.optical_agent import AgentEvidence
|
| 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 |
-
if
|
| 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 |
-
if
|
| 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 |
-
return {
|
| 316 |
-
"test": "Wavelet Coefficients",
|
| 317 |
-
"hf_kurtosis": round(kurt, 4),
|
| 318 |
-
"score": score,
|
| 319 |
-
"note": note,
|
| 320 |
-
}
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
# βββ Main Agent Entry Point βββββββββββββββββββββββββββββββββββββββββ
|
| 324 |
-
def run_statistical_agent(img: Image.Image) -> AgentEvidence:
|
| 325 |
-
"""Run all statistical priors tests."""
|
| 326 |
-
findings = []
|
| 327 |
-
scores = []
|
| 328 |
-
|
| 329 |
-
for fn in [analyze_dct_distribution, analyze_benford, analyze_gradient_sparsity,
|
| 330 |
-
analyze_local_kurtosis, analyze_color_histogram, analyze_wavelet_coefficients]:
|
| 331 |
-
try:
|
| 332 |
-
result = fn(img)
|
| 333 |
-
findings.append(result)
|
| 334 |
-
scores.append(result["score"])
|
| 335 |
-
except Exception as e:
|
| 336 |
-
findings.append({"test": fn.__name__, "error": str(e), "score": 0})
|
| 337 |
-
|
| 338 |
-
avg_score = float(np.mean(scores)) if scores else 0.0
|
| 339 |
-
confidence = min(1.0, 0.5 + 0.5 * abs(avg_score))
|
| 340 |
-
|
| 341 |
-
violations = [f["test"] for f in findings if f.get("score", 0) > 0.2]
|
| 342 |
-
compliant = [f["test"] for f in findings if f.get("score", 0) < -0.1]
|
| 343 |
-
|
| 344 |
-
if violations:
|
| 345 |
-
rationale = f"Statistical violations: {', '.join(violations)}."
|
| 346 |
-
elif compliant:
|
| 347 |
-
rationale = f"Natural statistics confirmed: {', '.join(compliant)}."
|
| 348 |
-
else:
|
| 349 |
-
rationale = "Statistical analysis inconclusive."
|
| 350 |
-
|
| 351 |
for f in findings:
|
| 352 |
-
if f.get("note"):
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
return AgentEvidence(
|
| 356 |
-
agent_name="Statistical Priors Agent",
|
| 357 |
-
violation_score=np.clip(avg_score, -1, 1),
|
| 358 |
-
confidence=confidence,
|
| 359 |
-
failure_prob=max(0.0, 1.0 - len(scores) / 6),
|
| 360 |
-
rationale=rationale,
|
| 361 |
-
sub_findings=findings,
|
| 362 |
-
)
|
|
|
|
| 1 |
+
"""FORENSIQ β Statistical Priors Agent (22 features)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
from PIL import Image
|
| 4 |
from scipy.fftpack import dct
|
| 5 |
+
from scipy.stats import kurtosis as sp_kurt, skew as sp_skew, entropy as sp_entropy
|
| 6 |
+
from scipy.ndimage import gaussian_filter, sobel, uniform_filter
|
| 7 |
from typing import Dict, Any
|
|
|
|
| 8 |
from agents.optical_agent import AgentEvidence
|
| 9 |
|
| 10 |
+
def _g(img): return np.array(img.convert("L")).astype(np.float64)
|
| 11 |
+
def _rgb(img): return np.array(img.convert("RGB")).astype(np.float64)
|
| 12 |
+
|
| 13 |
+
def t01_dct_kurtosis(img):
|
| 14 |
+
gray=_g(img); h,w=gray.shape; hc,wc=(h//8)*8,(w//8)*8; gray=gray[:hc,:wc]
|
| 15 |
+
coeffs=[]
|
| 16 |
+
for i in range(0,hc,8):
|
| 17 |
+
for j in range(0,wc,8):
|
| 18 |
+
b=gray[i:i+8,j:j+8]; d=dct(dct(b.T,norm="ortho").T,norm="ortho"); ac=d.copy(); ac[0,0]=0
|
| 19 |
+
coeffs.extend(ac.ravel().tolist())
|
| 20 |
+
c=np.array(coeffs); c=c[c!=0]
|
| 21 |
+
if len(c)<100: return {"test":"DCT Kurtosis","score":0.0,"note":"Insufficient data"}
|
| 22 |
+
k=float(sp_kurt(c,fisher=True))
|
| 23 |
+
if k>4.5: s,n=-0.4,f"Laplacian DCT (ΞΊ={k:.2f})"
|
| 24 |
+
elif k<2.0: s,n=0.5,f"Gaussian DCT (ΞΊ={k:.2f})"
|
| 25 |
+
elif k<3.5: s,n=0.2,f"Borderline (ΞΊ={k:.2f})"
|
| 26 |
+
else: s,n=-0.1,f"Near-natural (ΞΊ={k:.2f})"
|
| 27 |
+
return {"test":"DCT Kurtosis","kurtosis":round(k,4),"score":s,"note":n}
|
| 28 |
+
|
| 29 |
+
def t02_benford(img):
|
| 30 |
+
gray=_g(img); h,w=gray.shape; hc,wc=(h//8)*8,(w//8)*8; gray=gray[:hc,:wc]
|
| 31 |
+
coeffs=[]
|
| 32 |
+
for i in range(0,hc,8):
|
| 33 |
+
for j in range(0,wc,8):
|
| 34 |
+
coeffs.extend(np.abs(dct(dct(gray[i:i+8,j:j+8].T,norm="ortho").T,norm="ortho").ravel()).tolist())
|
| 35 |
+
c=np.array(coeffs); nz=c[c>0]
|
| 36 |
+
if len(nz)<100: return {"test":"Benford's Law","score":0.0,"note":"Insufficient"}
|
| 37 |
+
lv=np.floor(np.log10(nz+1e-12)); fd=np.floor(nz/(10**lv)).astype(int); fd=fd[(fd>=1)&(fd<=9)]
|
| 38 |
+
obs=np.array([np.sum(fd==d) for d in range(1,10)],dtype=float); obs/=(obs.sum()+1e-9)
|
| 39 |
+
ben=np.log10(1+1.0/np.arange(1,10))
|
| 40 |
+
chi2=float(np.sum((obs-ben)**2/(ben+1e-9)))
|
| 41 |
+
if chi2<0.005: s,n=-0.4,f"Excellent Benford fit (ΟΒ²={chi2:.5f})"
|
| 42 |
+
elif chi2<0.02: s,n=-0.1,f"Good fit (ΟΒ²={chi2:.5f})"
|
| 43 |
+
elif chi2<0.05: s,n=0.3,f"Moderate deviation (ΟΒ²={chi2:.5f})"
|
| 44 |
+
else: s,n=0.6,f"Strong violation (ΟΒ²={chi2:.5f})"
|
| 45 |
+
return {"test":"Benford's Law","chi2":round(chi2,6),"observed":obs.tolist(),"benford_expected":ben.tolist(),"score":s,"note":n}
|
| 46 |
+
|
| 47 |
+
def t03_gradient_sparsity(img):
|
| 48 |
+
gray=_g(img); gx=np.diff(gray,axis=1).ravel(); gy=np.diff(gray,axis=0).ravel()
|
| 49 |
+
ag=np.concatenate([gx,gy]); k=float(sp_kurt(ag,fisher=True))
|
| 50 |
+
thr=np.std(ag)*0.1; sp=float(np.mean(np.abs(ag)<thr))
|
| 51 |
+
if k>5 and sp>0.4: s,n=-0.4,f"Sparse gradients (ΞΊ={k:.2f}, sp={sp:.2f})"
|
| 52 |
+
elif k<2: s,n=0.5,f"Low kurtosis ({k:.2f})"
|
| 53 |
+
elif k<3.5: s,n=0.2,f"Borderline ({k:.2f})"
|
| 54 |
+
else: s,n=-0.1,f"Normal (ΞΊ={k:.2f})"
|
| 55 |
+
return {"test":"Gradient Sparsity","kurtosis":round(k,4),"sparsity":round(sp,4),"score":s,"note":n}
|
| 56 |
+
|
| 57 |
+
def t04_local_kurtosis(img):
|
| 58 |
+
gray=_g(img); h,w=gray.shape; bs=32; hc,wc=(h//bs)*bs,(w//bs)*bs; gray=gray[:hc,:wc]
|
| 59 |
+
lk=[]
|
| 60 |
+
for i in range(0,hc,bs):
|
| 61 |
+
for j in range(0,wc,bs):
|
| 62 |
+
b=gray[i:i+bs,j:j+bs].ravel()
|
| 63 |
+
if np.std(b)>1: lk.append(float(sp_kurt(b,fisher=True)))
|
| 64 |
+
if len(lk)<10: return {"test":"Local Kurtosis Map","score":0.0,"note":"Insufficient"}
|
| 65 |
+
std=float(np.std(lk))
|
| 66 |
+
if std>3: s,n=-0.3,f"High kurtosis variation (Ο={std:.2f})"
|
| 67 |
+
elif std<1: s,n=0.4,f"Uniform statistics (Ο={std:.2f})"
|
| 68 |
+
else: s,n=0.0,f"Moderate (Ο={std:.2f})"
|
| 69 |
+
return {"test":"Local Kurtosis Map","kurtosis_std":round(std,4),"score":s,"note":n}
|
| 70 |
+
|
| 71 |
+
def t05_color_histogram(img):
|
| 72 |
+
rgb=np.array(img.convert("RGB")); scores=[]
|
| 73 |
+
for c in range(3):
|
| 74 |
+
h,_=np.histogram(rgb[:,:,c].ravel(),bins=256,range=(0,256))
|
| 75 |
+
sm=gaussian_filter(h.astype(float),2)
|
| 76 |
+
scores.append(float(np.mean(np.abs(h-sm))/(np.mean(h)+1e-9)))
|
| 77 |
+
avg=float(np.mean(scores))
|
| 78 |
+
if avg<0.3: s,n=-0.2,f"Smooth histograms ({avg:.3f})"
|
| 79 |
+
elif avg>0.8: s,n=0.4,f"Irregular histograms ({avg:.3f})"
|
| 80 |
+
else: s,n=0.0,f"Histogram smoothness={avg:.3f}"
|
| 81 |
+
return {"test":"Color Histogram","smoothness":round(avg,4),"score":s,"note":n}
|
| 82 |
+
|
| 83 |
+
def t06_wavelet_kurtosis(img):
|
| 84 |
+
gray=_g(img); h,w=gray.shape; h2,w2=h//2*2,w//2*2; gray=gray[:h2,:w2]
|
| 85 |
+
lh=(gray[0::2,0::2]+gray[0::2,1::2]-gray[1::2,0::2]-gray[1::2,1::2])/4
|
| 86 |
+
hl=(gray[0::2,0::2]-gray[0::2,1::2]+gray[1::2,0::2]-gray[1::2,1::2])/4
|
| 87 |
+
hh=(gray[0::2,0::2]-gray[0::2,1::2]-gray[1::2,0::2]+gray[1::2,1::2])/4
|
| 88 |
+
hf=np.concatenate([lh.ravel(),hl.ravel(),hh.ravel()]); hf=hf[hf!=0]
|
| 89 |
+
if len(hf)<100: return {"test":"Wavelet Kurtosis","score":0.0,"note":"Insufficient"}
|
| 90 |
+
k=float(sp_kurt(hf,fisher=True))
|
| 91 |
+
if k>5: s,n=-0.3,f"Heavy-tailed wavelets (ΞΊ={k:.2f})"
|
| 92 |
+
elif k<1.5: s,n=0.4,f"Gaussian wavelets (ΞΊ={k:.2f})"
|
| 93 |
+
else: s,n=0.0,f"Wavelet ΞΊ={k:.2f}"
|
| 94 |
+
return {"test":"Wavelet Kurtosis","kurtosis":round(k,4),"score":s,"note":n}
|
| 95 |
+
|
| 96 |
+
def t07_entropy_map(img):
|
| 97 |
+
gray=_g(img); h,w=gray.shape; bs=32; ents=[]
|
| 98 |
+
for i in range(0,h-bs,bs):
|
| 99 |
+
for j in range(0,w-bs,bs):
|
| 100 |
+
b=gray[i:i+bs,j:j+bs].ravel().astype(int)
|
| 101 |
+
h_,_=np.histogram(b,bins=64,range=(0,256)); h_=h_.astype(float); h_/=(h_.sum()+1e-9)
|
| 102 |
+
ents.append(-float(np.sum(h_*np.log2(h_+1e-12))))
|
| 103 |
+
if len(ents)<4: return {"test":"Entropy Map","score":0.0,"note":"Too small"}
|
| 104 |
+
std=float(np.std(ents)); mn=float(np.mean(ents))
|
| 105 |
+
if std>0.5: s,n=-0.2,f"Varied local entropy (Ο={std:.2f})"
|
| 106 |
+
elif std<0.15: s,n=0.3,f"Uniform entropy (Ο={std:.2f})"
|
| 107 |
+
else: s,n=0.0,f"Entropy Ο={std:.2f}"
|
| 108 |
+
return {"test":"Entropy Map","entropy_std":round(std,4),"mean":round(mn,4),"score":s,"note":n}
|
| 109 |
+
|
| 110 |
+
def t08_edge_orientation(img):
|
| 111 |
+
gray=_g(img); gx=sobel(gray,1); gy=sobel(gray,0); mag=np.hypot(gx,gy)
|
| 112 |
+
strong=mag>np.percentile(mag,80); angles=np.arctan2(gy[strong],gx[strong])
|
| 113 |
+
hist,_=np.histogram(angles,bins=36,range=(-np.pi,np.pi)); hist=hist.astype(float); hist/=(hist.sum()+1e-9)
|
| 114 |
+
ent=-float(np.sum(hist*np.log(hist+1e-9)))
|
| 115 |
+
max_ent=np.log(36)
|
| 116 |
+
norm_ent=ent/max_ent
|
| 117 |
+
if norm_ent<0.85: s,n=-0.2,f"Directional edges (entropy={norm_ent:.3f})"
|
| 118 |
+
elif norm_ent>0.95: s,n=0.2,f"Isotropic edges ({norm_ent:.3f})"
|
| 119 |
+
else: s,n=0.0,f"Edge entropy={norm_ent:.3f}"
|
| 120 |
+
return {"test":"Edge Orientation","entropy":round(norm_ent,4),"score":s,"note":n}
|
| 121 |
+
|
| 122 |
+
def t09_lbp_distribution(img):
|
| 123 |
+
gray=np.array(img.convert("L")); h,w=gray.shape
|
| 124 |
+
# Simplified LBP
|
| 125 |
+
lbp=np.zeros((h-2,w-2),dtype=int)
|
| 126 |
+
for dy,dx,bit in [(-1,-1,0),(-1,0,1),(-1,1,2),(0,1,3),(1,1,4),(1,0,5),(1,-1,6),(0,-1,7)]:
|
| 127 |
+
lbp|=((gray[1+dy:h-1+dy,1+dx:w-1+dx]>=gray[1:h-1,1:w-1]).astype(int)<<bit)
|
| 128 |
+
hist,_=np.histogram(lbp.ravel(),bins=256,range=(0,256)); hist=hist.astype(float); hist/=(hist.sum()+1e-9)
|
| 129 |
+
# Uniform LBP patterns (β€2 transitions) dominate in natural images
|
| 130 |
+
uniform=0
|
| 131 |
+
for v in range(256):
|
| 132 |
+
b=format(v,'08b'); t=sum(1 for i in range(7) if b[i]!=b[i+1])+int(b[0]!=b[7])
|
| 133 |
+
if t<=2: uniform+=hist[v]
|
| 134 |
+
if uniform>0.6: s,n=-0.2,f"Natural LBP (uniform={uniform:.2%})"
|
| 135 |
+
elif uniform<0.3: s,n=0.3,f"Non-uniform LBP ({uniform:.2%})"
|
| 136 |
+
else: s,n=0.0,f"LBP uniform={uniform:.2%}"
|
| 137 |
+
return {"test":"LBP Distribution","uniform_ratio":round(uniform,4),"score":s,"note":n}
|
| 138 |
+
|
| 139 |
+
def t10_cooccurrence(img):
|
| 140 |
+
gray=(np.array(img.convert("L"))//16).astype(int); h,w=gray.shape # Quantize to 16 levels
|
| 141 |
+
glcm=np.zeros((16,16))
|
| 142 |
+
for i in range(h):
|
| 143 |
+
for j in range(w-1):
|
| 144 |
+
glcm[gray[i,j],gray[i,j+1]]+=1
|
| 145 |
+
glcm/=(glcm.sum()+1e-9)
|
| 146 |
+
# Energy (angular second moment)
|
| 147 |
+
energy=float(np.sum(glcm**2))
|
| 148 |
+
# Homogeneity
|
| 149 |
+
I,J=np.mgrid[0:16,0:16]; homog=float(np.sum(glcm/(1+np.abs(I-J))))
|
| 150 |
+
if energy<0.05 and homog>0.5: s,n=-0.2,f"Natural texture (E={energy:.4f}, H={homog:.3f})"
|
| 151 |
+
elif energy>0.2: s,n=0.3,f"Flat/repetitive (E={energy:.4f})"
|
| 152 |
+
else: s,n=0.0,f"GLCM E={energy:.4f}, H={homog:.3f}"
|
| 153 |
+
return {"test":"Co-occurrence Matrix","energy":round(energy,4),"homogeneity":round(homog,4),"score":s,"note":n}
|
| 154 |
+
|
| 155 |
+
def t11_block_variance(img):
|
| 156 |
+
gray=_g(img); h,w=gray.shape; bs=8; hc,wc=(h//bs)*bs,(w//bs)*bs
|
| 157 |
+
gray=gray[:hc,:wc]; bvars=[]
|
| 158 |
+
for i in range(0,hc,bs):
|
| 159 |
+
for j in range(0,wc,bs):
|
| 160 |
+
bvars.append(float(np.var(gray[i:i+bs,j:j+bs])))
|
| 161 |
+
bv=np.array(bvars)
|
| 162 |
+
# ANOVA-like test: variance of variances
|
| 163 |
+
vov=float(np.std(bv))/(float(np.mean(bv))+1e-9)
|
| 164 |
+
if vov>1: s,n=-0.2,f"Varied block variance (VoV={vov:.3f})"
|
| 165 |
+
elif vov<0.3: s,n=0.3,f"Uniform block variance ({vov:.3f})"
|
| 166 |
+
else: s,n=0.0,f"VoV={vov:.3f}"
|
| 167 |
+
return {"test":"Block Variance ANOVA","vov":round(vov,4),"score":s,"note":n}
|
| 168 |
+
|
| 169 |
+
def t12_gradient_magnitude(img):
|
| 170 |
+
gray=_g(img); gm=np.hypot(sobel(gray,0),sobel(gray,1))
|
| 171 |
+
k=float(sp_kurt(gm.ravel(),fisher=True)); sk=float(sp_skew(gm.ravel()))
|
| 172 |
+
if k>5: s,n=-0.2,f"Heavy-tailed gradients (ΞΊ={k:.2f})"
|
| 173 |
+
elif k<2: s,n=0.3,f"Light-tailed ({k:.2f})"
|
| 174 |
+
else: s,n=0.0,f"Gradient ΞΊ={k:.2f}"
|
| 175 |
+
return {"test":"Gradient Magnitude Dist","kurtosis":round(k,3),"skewness":round(sk,3),"score":s,"note":n}
|
| 176 |
+
|
| 177 |
+
def t13_spatial_correlation(img):
|
| 178 |
+
gray=_g(img); h,w=gray.shape; step=max(1,h*w//200000)
|
| 179 |
+
ac1=float(np.corrcoef(gray[:,:-1].ravel()[::step],gray[:,1:].ravel()[::step])[0,1])
|
| 180 |
+
ac5=float(np.corrcoef(gray[:,:-5].ravel()[::step],gray[:,5:].ravel()[::step])[0,1])
|
| 181 |
+
decay=ac1-ac5
|
| 182 |
+
if 0.05<decay<0.3: s,n=-0.2,f"Natural correlation decay ({decay:.3f})"
|
| 183 |
+
elif decay<0.01: s,n=0.3,f"Flat correlation ({decay:.3f})"
|
| 184 |
+
else: s,n=0.0,f"Decay={decay:.3f}"
|
| 185 |
+
return {"test":"Spatial Correlation Decay","decay":round(decay,4),"score":s,"note":n}
|
| 186 |
+
|
| 187 |
+
def t14_dct_skewness(img):
|
| 188 |
+
gray=_g(img); h,w=gray.shape; hc,wc=(h//8)*8,(w//8)*8; gray=gray[:hc,:wc]
|
| 189 |
+
coeffs=[]
|
| 190 |
+
for i in range(0,hc,8):
|
| 191 |
+
for j in range(0,wc,8):
|
| 192 |
+
d=dct(dct(gray[i:i+8,j:j+8].T,norm="ortho").T,norm="ortho"); ac=d.copy(); ac[0,0]=0
|
| 193 |
+
coeffs.extend(ac.ravel().tolist())
|
| 194 |
+
c=np.array(coeffs); c=c[c!=0]
|
| 195 |
+
if len(c)<100: return {"test":"DCT Skewness","score":0.0,"note":"Insufficient"}
|
| 196 |
+
sk=float(sp_skew(c))
|
| 197 |
+
if abs(sk)<0.1: s,n=-0.2,f"Symmetric DCT (skew={sk:.3f})"
|
| 198 |
+
elif abs(sk)>0.5: s,n=0.3,f"Skewed DCT ({sk:.3f})"
|
| 199 |
+
else: s,n=0.0,f"DCT skew={sk:.3f}"
|
| 200 |
+
return {"test":"DCT Skewness","skewness":round(sk,4),"score":s,"note":n}
|
| 201 |
+
|
| 202 |
+
def t15_saturation_distribution(img):
|
| 203 |
+
rgb=np.array(img.convert("RGB")).astype(float)
|
| 204 |
+
mx=np.max(rgb,axis=-1); mn=np.min(rgb,axis=-1)
|
| 205 |
+
sat=(mx-mn)/(mx+1e-9); sat_flat=sat.ravel()
|
| 206 |
+
k=float(sp_kurt(sat_flat,fisher=True))
|
| 207 |
+
if k>3: s,n=-0.2,f"Natural saturation (ΞΊ={k:.2f})"
|
| 208 |
+
elif k<1: s,n=0.3,f"Unusual saturation ({k:.2f})"
|
| 209 |
+
else: s,n=0.0,f"Saturation ΞΊ={k:.2f}"
|
| 210 |
+
return {"test":"Saturation Distribution","kurtosis":round(k,3),"score":s,"note":n}
|
| 211 |
+
|
| 212 |
+
def t16_luminance_gradient_ratio(img):
|
| 213 |
+
gray=_g(img); gx=np.abs(np.diff(gray,axis=1)); gy=np.abs(np.diff(gray,axis=0))
|
| 214 |
+
hg=float(np.mean(gx)); vg=float(np.mean(gy))
|
| 215 |
+
ratio=hg/(vg+1e-9)
|
| 216 |
+
if 0.7<ratio<1.4: s,n=-0.1,f"Balanced H/V gradients ({ratio:.3f})"
|
| 217 |
+
elif ratio>2 or ratio<0.5: s,n=0.2,f"Extreme H/V bias ({ratio:.3f})"
|
| 218 |
+
else: s,n=0.0,f"H/V ratio={ratio:.3f}"
|
| 219 |
+
return {"test":"H/V Gradient Ratio","ratio":round(ratio,3),"score":s,"note":n}
|
| 220 |
+
|
| 221 |
+
def t17_pixel_uniqueness(img):
|
| 222 |
+
gray=np.array(img.convert("L")); total=gray.size; unique=len(np.unique(gray))
|
| 223 |
+
ratio=unique/256
|
| 224 |
+
if ratio>0.9: s,n=-0.1,f"Full tonal range ({unique} levels)"
|
| 225 |
+
elif ratio<0.5: s,n=0.2,f"Limited range ({unique} levels)"
|
| 226 |
+
else: s,n=0.0,f"{unique} levels"
|
| 227 |
+
return {"test":"Pixel Uniqueness","levels":unique,"score":s,"note":n}
|
| 228 |
+
|
| 229 |
+
def t18_global_entropy(img):
|
| 230 |
+
gray=np.array(img.convert("L")); hist,_=np.histogram(gray,bins=256,range=(0,256))
|
| 231 |
+
hist=hist.astype(float); hist/=(hist.sum()+1e-9)
|
| 232 |
+
ent=-float(np.sum(hist*np.log2(hist+1e-12)))
|
| 233 |
+
if 6<ent<7.8: s,n=-0.2,f"Natural entropy ({ent:.3f})"
|
| 234 |
+
elif ent<5: s,n=0.3,f"Low entropy ({ent:.3f})"
|
| 235 |
+
else: s,n=0.0,f"Entropy={ent:.3f}"
|
| 236 |
+
return {"test":"Global Entropy","entropy":round(ent,4),"score":s,"note":n}
|
| 237 |
+
|
| 238 |
+
def t19_power_law_fit(img):
|
| 239 |
+
gray=_g(img); gm=np.hypot(sobel(gray,0),sobel(gray,1)).ravel()
|
| 240 |
+
gm=gm[gm>1]; hist,edges=np.histogram(gm,bins=50); hist=hist.astype(float)+1
|
| 241 |
+
centers=(edges[:-1]+edges[1:])/2; valid=hist>1
|
| 242 |
+
if np.sum(valid)<5: return {"test":"Power Law Gradient","score":0.0,"note":"Insufficient"}
|
| 243 |
+
try:
|
| 244 |
+
c=np.polyfit(np.log(centers[valid]),np.log(hist[valid]),1); slope=float(c[0])
|
| 245 |
+
except: slope=0
|
| 246 |
+
if -3<slope<-1: s,n=-0.2,f"Power-law gradients (Ξ±={slope:.2f})"
|
| 247 |
+
elif slope>-0.5: s,n=0.3,f"Non-power-law ({slope:.2f})"
|
| 248 |
+
else: s,n=0.0,f"Slope={slope:.2f}"
|
| 249 |
+
return {"test":"Power Law Gradient","slope":round(slope,3),"score":s,"note":n}
|
| 250 |
+
|
| 251 |
+
def t20_contrast_distribution(img):
|
| 252 |
+
gray=_g(img); h,w=gray.shape; bs=16
|
| 253 |
+
contrasts=[]
|
| 254 |
+
for i in range(0,h-bs,bs):
|
| 255 |
+
for j in range(0,w-bs,bs):
|
| 256 |
+
b=gray[i:i+bs,j:j+bs]; contrasts.append(float(np.max(b)-np.min(b)))
|
| 257 |
+
c=np.array(contrasts)
|
| 258 |
+
if len(c)<10: return {"test":"Contrast Distribution","score":0.0,"note":"Insufficient"}
|
| 259 |
+
k=float(sp_kurt(c,fisher=True))
|
| 260 |
+
if k>2: s,n=-0.2,f"Natural contrast variation (ΞΊ={k:.2f})"
|
| 261 |
+
elif k<0.5: s,n=0.2,f"Uniform contrast ({k:.2f})"
|
| 262 |
+
else: s,n=0.0,f"Contrast ΞΊ={k:.2f}"
|
| 263 |
+
return {"test":"Contrast Distribution","kurtosis":round(k,3),"score":s,"note":n}
|
| 264 |
+
|
| 265 |
+
def t21_joint_histogram(img):
|
| 266 |
+
rgb=np.array(img.convert("RGB")); r,g=rgb[:,:,0].ravel(),rgb[:,:,1].ravel()
|
| 267 |
+
step=max(1,len(r)//100000)
|
| 268 |
+
h2d,_,_=np.histogram2d(r[::step],g[::step],bins=32,range=[[0,256],[0,256]])
|
| 269 |
+
h2d/=(h2d.sum()+1e-9)
|
| 270 |
+
# Mutual information
|
| 271 |
+
hr=np.sum(h2d,axis=1); hg=np.sum(h2d,axis=0)
|
| 272 |
+
mi=float(np.sum(h2d*np.log2(h2d/(np.outer(hr,hg)+1e-12)+1e-12)))
|
| 273 |
+
if mi>0.5: s,n=-0.2,f"Natural color correlation (MI={mi:.3f})"
|
| 274 |
+
elif mi<0.1: s,n=0.2,f"Weak color correlation ({mi:.3f})"
|
| 275 |
+
else: s,n=0.0,f"MI={mi:.3f}"
|
| 276 |
+
return {"test":"Joint Color Histogram","mi":round(mi,4),"score":s,"note":n}
|
| 277 |
+
|
| 278 |
+
def t22_run_length(img):
|
| 279 |
+
gray=np.array(img.convert("L")); row=gray[gray.shape[0]//2,:]
|
| 280 |
+
runs=[]; cur=1
|
| 281 |
+
for i in range(1,len(row)):
|
| 282 |
+
if row[i]==row[i-1]: cur+=1
|
| 283 |
+
else: runs.append(cur); cur=1
|
| 284 |
+
runs.append(cur); runs=np.array(runs)
|
| 285 |
+
avg_run=float(np.mean(runs)); max_run=int(np.max(runs))
|
| 286 |
+
if 1<avg_run<5: s,n=-0.2,f"Natural run lengths (avg={avg_run:.2f})"
|
| 287 |
+
elif avg_run>10: s,n=0.3,f"Long runs ({avg_run:.2f}) β flat patches"
|
| 288 |
+
else: s,n=0.0,f"Run avg={avg_run:.2f}"
|
| 289 |
+
return {"test":"Run Length Analysis","avg_run":round(avg_run,3),"score":s,"note":n}
|
| 290 |
+
|
| 291 |
+
ALL_TESTS=[t01_dct_kurtosis,t02_benford,t03_gradient_sparsity,t04_local_kurtosis,t05_color_histogram,
|
| 292 |
+
t06_wavelet_kurtosis,t07_entropy_map,t08_edge_orientation,t09_lbp_distribution,t10_cooccurrence,
|
| 293 |
+
t11_block_variance,t12_gradient_magnitude,t13_spatial_correlation,t14_dct_skewness,
|
| 294 |
+
t15_saturation_distribution,t16_luminance_gradient_ratio,t17_pixel_uniqueness,t18_global_entropy,
|
| 295 |
+
t19_power_law_fit,t20_contrast_distribution,t21_joint_histogram,t22_run_length]
|
| 296 |
+
|
| 297 |
+
def run_statistical_agent(img):
|
| 298 |
+
findings,scores=[],[]
|
| 299 |
+
for fn in ALL_TESTS:
|
| 300 |
+
try: r=fn(img); findings.append(r); scores.append(r["score"])
|
| 301 |
+
except Exception as e: findings.append({"test":fn.__name__,"error":str(e),"score":0})
|
| 302 |
+
avg=float(np.mean(scores)) if scores else 0.0; conf=min(1.0,0.5+0.5*abs(avg))
|
| 303 |
+
viol=[f["test"] for f in findings if f.get("score",0)>0.2]
|
| 304 |
+
comp=[f["test"] for f in findings if f.get("score",0)<-0.1]
|
| 305 |
+
rat=f"Statistical violations: {', '.join(viol)}." if viol else f"Natural statistics: {', '.join(comp)}." if comp else "Statistical inconclusive."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
for f in findings:
|
| 307 |
+
if f.get("note"): rat+=f" [{f['test']}]: {f['note']}."
|
| 308 |
+
return AgentEvidence("Statistical Priors Agent",np.clip(avg,-1,1),conf,max(0,1-len(scores)/len(ALL_TESTS)),rat,findings)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|