Upload agents/model_agent.py with huggingface_hub
Browse files- agents/model_agent.py +245 -353
agents/model_agent.py
CHANGED
|
@@ -1,360 +1,252 @@
|
|
| 1 |
-
"""
|
| 2 |
-
FORENSIQ β Generative Model Agent
|
| 3 |
-
Detects architecture-specific signatures:
|
| 4 |
-
- Frequency grid artifacts (8Γ8, 16Γ16 periodic patterns from GANs)
|
| 5 |
-
- Diffusion residuals (spectral notches at step noise harmonics)
|
| 6 |
-
- Model fingerprinting (frequency-domain generator attribution)
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
import numpy as np
|
| 10 |
from PIL import Image
|
| 11 |
from scipy.signal import find_peaks
|
| 12 |
-
from scipy.ndimage import gaussian_filter
|
| 13 |
from typing import Dict, Any
|
| 14 |
-
|
| 15 |
from agents.optical_agent import AgentEvidence
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def
|
| 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 |
-
elif
|
| 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 |
-
h,
|
| 185 |
-
cy,
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
if
|
| 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 |
-
"score": score,
|
| 259 |
-
"note": note,
|
| 260 |
-
}
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
# βββ VAE Boundary Artifacts βββββββββββββββββββββββββββββββββββββββββ
|
| 264 |
-
def analyze_vae_boundaries(img: Image.Image) -> Dict[str, Any]:
|
| 265 |
-
"""
|
| 266 |
-
VAE-based generators (Stable Diffusion) process in latent patches.
|
| 267 |
-
This can create subtle boundary artifacts at 64x64 or 32x32 grid.
|
| 268 |
-
"""
|
| 269 |
-
gray = np.array(img.convert("L")).astype(np.float64)
|
| 270 |
-
h, w = gray.shape
|
| 271 |
-
|
| 272 |
-
# Check for grid artifacts at common VAE patch sizes
|
| 273 |
-
best_score = 0.0
|
| 274 |
-
best_size = 0
|
| 275 |
-
best_ratio = 1.0
|
| 276 |
-
|
| 277 |
-
for patch_size in [32, 64, 128]:
|
| 278 |
-
if h < patch_size * 2 or w < patch_size * 2:
|
| 279 |
-
continue
|
| 280 |
-
|
| 281 |
-
h_crop = (h // patch_size) * patch_size
|
| 282 |
-
w_crop = (w // patch_size) * patch_size
|
| 283 |
-
g = gray[:h_crop, :w_crop]
|
| 284 |
-
|
| 285 |
-
# Measure intensity discontinuity at patch boundaries
|
| 286 |
-
boundary_diffs = []
|
| 287 |
-
interior_diffs = []
|
| 288 |
-
|
| 289 |
-
for i in range(1, h_crop):
|
| 290 |
-
row_diff = np.abs(g[i, :] - g[i - 1, :])
|
| 291 |
-
if i % patch_size == 0:
|
| 292 |
-
boundary_diffs.append(float(np.mean(row_diff)))
|
| 293 |
-
elif i % patch_size != 1:
|
| 294 |
-
interior_diffs.append(float(np.mean(row_diff)))
|
| 295 |
-
|
| 296 |
-
if boundary_diffs and interior_diffs:
|
| 297 |
-
ratio = float(np.mean(boundary_diffs)) / (float(np.mean(interior_diffs)) + 1e-9)
|
| 298 |
-
if ratio > best_ratio:
|
| 299 |
-
best_ratio = ratio
|
| 300 |
-
best_size = patch_size
|
| 301 |
-
|
| 302 |
-
if best_ratio > 1.3:
|
| 303 |
-
score = 0.4
|
| 304 |
-
note = f"VAE boundary artifacts at {best_size}px grid (ratio={best_ratio:.3f})"
|
| 305 |
-
elif best_ratio > 1.1:
|
| 306 |
-
score = 0.2
|
| 307 |
-
note = f"Weak boundary artifacts at {best_size}px (ratio={best_ratio:.3f})"
|
| 308 |
-
else:
|
| 309 |
-
score = -0.1
|
| 310 |
-
note = f"No VAE boundary artifacts (max ratio={best_ratio:.3f})"
|
| 311 |
-
|
| 312 |
-
return {
|
| 313 |
-
"test": "VAE Boundary Artifacts",
|
| 314 |
-
"best_boundary_ratio": round(best_ratio, 4),
|
| 315 |
-
"best_patch_size": best_size,
|
| 316 |
-
"score": score,
|
| 317 |
-
"note": note,
|
| 318 |
-
}
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
# βββ Main Agent Entry Point βββββββββββββββββββββββββββββββββββββββββ
|
| 322 |
-
def run_model_agent(img: Image.Image) -> AgentEvidence:
|
| 323 |
-
"""Run all generative model detection tests."""
|
| 324 |
-
findings = []
|
| 325 |
-
scores = []
|
| 326 |
-
|
| 327 |
-
for fn in [analyze_frequency_grid, analyze_diffusion_residuals, analyze_model_fingerprint,
|
| 328 |
-
analyze_upsampling_checkerboard, analyze_vae_boundaries]:
|
| 329 |
-
try:
|
| 330 |
-
result = fn(img)
|
| 331 |
-
findings.append(result)
|
| 332 |
-
scores.append(result["score"])
|
| 333 |
-
except Exception as e:
|
| 334 |
-
findings.append({"test": fn.__name__, "error": str(e), "score": 0})
|
| 335 |
-
|
| 336 |
-
avg_score = float(np.mean(scores)) if scores else 0.0
|
| 337 |
-
confidence = min(1.0, 0.5 + 0.5 * abs(avg_score))
|
| 338 |
-
|
| 339 |
-
violations = [f["test"] for f in findings if f.get("score", 0) > 0.2]
|
| 340 |
-
compliant = [f["test"] for f in findings if f.get("score", 0) < -0.1]
|
| 341 |
-
|
| 342 |
-
if violations:
|
| 343 |
-
rationale = f"Generative model signatures detected: {', '.join(violations)}."
|
| 344 |
-
elif compliant:
|
| 345 |
-
rationale = f"No generator artifacts found: {', '.join(compliant)}."
|
| 346 |
-
else:
|
| 347 |
-
rationale = "Generator analysis inconclusive."
|
| 348 |
-
|
| 349 |
for f in findings:
|
| 350 |
-
if f.get("note"):
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
return AgentEvidence(
|
| 354 |
-
agent_name="Generative Model Agent",
|
| 355 |
-
violation_score=np.clip(avg_score, -1, 1),
|
| 356 |
-
confidence=confidence,
|
| 357 |
-
failure_prob=max(0.0, 1.0 - len(scores) / 5),
|
| 358 |
-
rationale=rationale,
|
| 359 |
-
sub_findings=findings,
|
| 360 |
-
)
|
|
|
|
| 1 |
+
"""FORENSIQ β Generative Model Agent (15 features)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
from PIL import Image
|
| 4 |
from scipy.signal import find_peaks
|
| 5 |
+
from scipy.ndimage import gaussian_filter, label
|
| 6 |
from typing import Dict, Any
|
|
|
|
| 7 |
from agents.optical_agent import AgentEvidence
|
| 8 |
|
| 9 |
+
def _g(img): return np.array(img.convert("L")).astype(np.float64)
|
| 10 |
+
|
| 11 |
+
def m01_fft_grid_8x8(img):
|
| 12 |
+
gray=_g(img); h,w=gray.shape; fft=np.fft.fftshift(np.fft.fft2(gray)); mag=np.log(np.abs(fft)+1)
|
| 13 |
+
cy,cx=h//2,w//2; rp=mag[cy,:]; cp=mag[:,cx]
|
| 14 |
+
rpeaks,_=find_peaks(rp,distance=5,prominence=0.3); cpeaks,_=find_peaks(cp,distance=5,prominence=0.3)
|
| 15 |
+
def check(peaks,sz):
|
| 16 |
+
if len(peaks)<3: return 0.0
|
| 17 |
+
sp=np.diff(sorted(peaks)); e8=sz/8; e16=sz/16
|
| 18 |
+
m8=np.sum(np.abs(sp-e8)<e8*0.15); m16=np.sum(np.abs(sp-e16)<e16*0.15)
|
| 19 |
+
return float(max(m8,m16)/max(len(sp),1))
|
| 20 |
+
gs=(check(rpeaks,w)+check(cpeaks,h))/2
|
| 21 |
+
if gs>0.4: s,n=0.7,f"8Γ8 grid artifacts (periodicity={gs:.2f})"
|
| 22 |
+
elif gs>0.2: s,n=0.3,f"Weak grid patterns ({gs:.2f})"
|
| 23 |
+
else: s,n=-0.2,"No grid artifacts"
|
| 24 |
+
return {"test":"FFT Grid 8Γ8","periodicity":round(gs,4),"score":s,"note":n,"magnitude_spectrum":mag}
|
| 25 |
+
|
| 26 |
+
def m02_fft_grid_16x16(img):
|
| 27 |
+
gray=_g(img); h,w=gray.shape; fft=np.fft.fftshift(np.fft.fft2(gray)); mag=np.log(np.abs(fft)+1)
|
| 28 |
+
cy,cx=h//2,w//2
|
| 29 |
+
# Check specifically for 16Γ16 period
|
| 30 |
+
e16_h,e16_w=h//16,w//16
|
| 31 |
+
peaks_h=[mag[cy,cx+k*e16_w] if cx+k*e16_w<w else 0 for k in range(1,8)]
|
| 32 |
+
peaks_v=[mag[cy+k*e16_h,cx] if cy+k*e16_h<h else 0 for k in range(1,8)]
|
| 33 |
+
avg_peak=(float(np.mean(peaks_h))+float(np.mean(peaks_v)))/2
|
| 34 |
+
bg=float(np.median(mag))
|
| 35 |
+
ratio=avg_peak/(bg+1e-9)
|
| 36 |
+
if ratio>1.5: s,n=0.5,f"16Γ16 spectral peaks (ratio={ratio:.2f})"
|
| 37 |
+
elif ratio>1.2: s,n=0.2,f"Mild 16Γ16 peaks ({ratio:.2f})"
|
| 38 |
+
else: s,n=-0.1,f"No 16Γ16 artifacts ({ratio:.2f})"
|
| 39 |
+
return {"test":"FFT Grid 16Γ16","peak_ratio":round(ratio,3),"score":s,"note":n}
|
| 40 |
+
|
| 41 |
+
def m03_spectral_slope(img):
|
| 42 |
+
gray=_g(img); h,w=gray.shape; fft=np.fft.fftshift(np.fft.fft2(gray)); power=np.abs(fft)**2
|
| 43 |
+
cy,cx=h//2,w//2; Y,X=np.mgrid[0:h,0:w]; R=np.sqrt((X-cx)**2+(Y-cy)**2).astype(int)
|
| 44 |
+
maxr=min(cy,cx); rp=np.zeros(maxr)
|
| 45 |
+
for r in range(maxr):
|
| 46 |
+
m=R==r
|
| 47 |
+
if m.any(): rp[r]=float(np.mean(power[m]))
|
| 48 |
+
rp=np.log(rp+1); freqs=np.arange(1,maxr); lf=np.log(freqs+1); lp=rp[1:maxr]
|
| 49 |
+
if len(lf)>10:
|
| 50 |
+
c=np.polyfit(lf,lp,1); slope=float(c[0]); dev=abs(slope-(-2.0))
|
| 51 |
+
else: slope=0; dev=2
|
| 52 |
+
if dev<0.5: s,n=-0.3,f"Natural 1/fΒ² slope ({slope:.2f})"
|
| 53 |
+
elif dev>1.5: s,n=0.3,f"Unnatural spectral slope ({slope:.2f})"
|
| 54 |
+
else: s,n=0.1,f"Slope deviation={dev:.2f}"
|
| 55 |
+
return {"test":"Spectral Slope 1/fΒ²","slope":round(slope,3),"score":s,"note":n}
|
| 56 |
+
|
| 57 |
+
def m04_diffusion_notches(img):
|
| 58 |
+
gray=_g(img); fft=np.fft.fftshift(np.fft.fft2(gray)); power=np.abs(fft)**2
|
| 59 |
+
h,w=power.shape; cy,cx=h//2,w//2; Y,X=np.mgrid[0:h,0:w]; R=np.sqrt((X-cx)**2+(Y-cy)**2).astype(int)
|
| 60 |
+
maxr=min(cy,cx); rp=np.zeros(maxr)
|
| 61 |
+
for r in range(maxr):
|
| 62 |
+
m=R==r
|
| 63 |
+
if m.any(): rp[r]=float(np.mean(power[m]))
|
| 64 |
+
rp=np.log(rp+1)
|
| 65 |
+
if len(rp)>20:
|
| 66 |
+
c=np.polyfit(np.log(np.arange(1,maxr)+1),rp[1:maxr],1); fitted=np.polyval(c,np.log(np.arange(1,maxr)+1))
|
| 67 |
+
res=rp[1:maxr]-fitted; notches,_=find_peaks(-res,prominence=0.5); nn=len(notches)
|
| 68 |
+
else: nn=0
|
| 69 |
+
if nn>3: s,n=0.5,f"{nn} spectral notches β diffusion signature"
|
| 70 |
+
elif nn>1: s,n=0.2,f"{nn} notches"
|
| 71 |
+
else: s,n=-0.1,"No diffusion notches"
|
| 72 |
+
return {"test":"Diffusion Notches","count":nn,"score":s,"note":n}
|
| 73 |
+
|
| 74 |
+
def m05_autocorrelation(img):
|
| 75 |
+
gray=_g(img); fft=np.fft.fft2(gray); power=np.abs(fft)**2
|
| 76 |
+
ac=np.real(np.fft.ifft2(power)); ac=np.fft.fftshift(ac); ac=ac/(ac.max()+1e-9)
|
| 77 |
+
h,w=ac.shape; cy,cx=h//2,w//2; acm=ac.copy()
|
| 78 |
+
re=max(h,w)//20; Y,X=np.mgrid[0:h,0:w]; cm=((X-cx)**2+(Y-cy)**2)<re**2; acm[cm]=0
|
| 79 |
+
ms=float(np.max(acm))
|
| 80 |
+
if ms>0.3: s,n=0.6,f"Strong secondary peak ({ms:.3f}) β GAN checkerboard"
|
| 81 |
+
elif ms>0.15: s,n=0.3,f"Moderate peak ({ms:.3f})"
|
| 82 |
+
else: s,n=-0.2,f"Natural autocorrelation ({ms:.3f})"
|
| 83 |
+
return {"test":"Autocorrelation Peak","max_secondary":round(ms,4),"score":s,"note":n}
|
| 84 |
+
|
| 85 |
+
def m06_checkerboard(img):
|
| 86 |
+
gray=_g(img); h,w=gray.shape
|
| 87 |
+
if h<10 or w<10: return {"test":"Checkerboard Pattern","score":0.0,"note":"Too small"}
|
| 88 |
+
ha=float(np.corrcoef(gray[:,:-2].ravel()[::100],gray[:,2:].ravel()[::100])[0,1])
|
| 89 |
+
va=float(np.corrcoef(gray[:-2,:].ravel()[::100],gray[2:,:].ravel()[::100])[0,1])
|
| 90 |
+
h1=float(np.corrcoef(gray[:,:-1].ravel()[::100],gray[:,1:].ravel()[::100])[0,1])
|
| 91 |
+
v1=float(np.corrcoef(gray[:-1,:].ravel()[::100],gray[1:,:].ravel()[::100])[0,1])
|
| 92 |
+
delta=((ha-h1)+(va-v1))/2
|
| 93 |
+
if delta>0.02: s,n=0.5,f"Checkerboard detected (Ξ={delta:.4f})"
|
| 94 |
+
elif delta>0.005: s,n=0.2,f"Mild checkerboard ({delta:.4f})"
|
| 95 |
+
else: s,n=-0.1,f"No checkerboard ({delta:.4f})"
|
| 96 |
+
return {"test":"Checkerboard Pattern","delta":round(delta,6),"score":s,"note":n}
|
| 97 |
+
|
| 98 |
+
def m07_vae_boundaries(img):
|
| 99 |
+
gray=_g(img); h,w=gray.shape; best_r,best_s=1.0,0
|
| 100 |
+
for ps in [32,64,128]:
|
| 101 |
+
if h<ps*2 or w<ps*2: continue
|
| 102 |
+
hc,wc=(h//ps)*ps,(w//ps)*ps; g=gray[:hc,:wc]
|
| 103 |
+
bd,it=[],[]
|
| 104 |
+
for i in range(1,hc):
|
| 105 |
+
rd=np.abs(g[i,:]-g[i-1,:])
|
| 106 |
+
if i%ps==0: bd.append(float(np.mean(rd)))
|
| 107 |
+
elif i%ps!=1: it.append(float(np.mean(rd)))
|
| 108 |
+
if bd and it:
|
| 109 |
+
r=float(np.mean(bd))/(float(np.mean(it))+1e-9)
|
| 110 |
+
if r>best_r: best_r=r; best_s=ps
|
| 111 |
+
if best_r>1.3: s,n=0.4,f"VAE boundaries at {best_s}px ({best_r:.3f})"
|
| 112 |
+
elif best_r>1.1: s,n=0.2,f"Weak boundaries ({best_r:.3f})"
|
| 113 |
+
else: s,n=-0.1,f"No VAE boundaries ({best_r:.3f})"
|
| 114 |
+
return {"test":"VAE Patch Boundaries","ratio":round(best_r,4),"score":s,"note":n}
|
| 115 |
+
|
| 116 |
+
def m08_spectral_symmetry(img):
|
| 117 |
+
gray=_g(img); fft=np.fft.fftshift(np.fft.fft2(gray)); mag=np.log(np.abs(fft)+1)
|
| 118 |
+
h,w=mag.shape; cy,cx=h//2,w//2
|
| 119 |
+
top=mag[:cy,:]; bot=np.flipud(mag[cy+1:,:])
|
| 120 |
+
left=mag[:,:cx]; right=np.fliplr(mag[:,cx+1:])
|
| 121 |
+
mh,mw=min(top.shape[0],bot.shape[0]),min(top.shape[1],bot.shape[1])
|
| 122 |
+
asym_tb=float(np.mean(np.abs(top[:mh,:mw]-bot[:mh,:mw])))
|
| 123 |
+
mh2,mw2=min(left.shape[0],right.shape[0]),min(left.shape[1],right.shape[1])
|
| 124 |
+
asym_lr=float(np.mean(np.abs(left[:mh2,:mw2]-right[:mh2,:mw2])))
|
| 125 |
+
asym=(asym_tb+asym_lr)/2
|
| 126 |
+
if asym<0.1: s,n=-0.1,f"Symmetric spectrum ({asym:.3f})"
|
| 127 |
+
elif asym>0.5: s,n=0.3,f"Asymmetric spectrum ({asym:.3f})"
|
| 128 |
+
else: s,n=0.0,f"Spectral asymmetry={asym:.3f}"
|
| 129 |
+
return {"test":"Spectral Symmetry","asymmetry":round(asym,4),"score":s,"note":n}
|
| 130 |
+
|
| 131 |
+
def m09_upsampling_stride(img):
|
| 132 |
+
gray=_g(img); h,w=gray.shape
|
| 133 |
+
# Check for stride-2 upsampling artifacts
|
| 134 |
+
even=gray[::2,::2]; odd=gray[1::2,1::2]
|
| 135 |
+
mh,mw=min(even.shape[0],odd.shape[0]),min(even.shape[1],odd.shape[1])
|
| 136 |
+
diff=float(np.mean(np.abs(even[:mh,:mw]-odd[:mh,:mw])))
|
| 137 |
+
mean_val=float(np.mean(gray))
|
| 138 |
+
norm_diff=diff/(mean_val+1e-9)
|
| 139 |
+
if norm_diff>0.1: s,n=-0.1,f"Natural stride variation ({norm_diff:.4f})"
|
| 140 |
+
elif norm_diff<0.01: s,n=0.3,f"Stride-2 artifacts ({norm_diff:.4f})"
|
| 141 |
+
else: s,n=0.0,f"Stride diff={norm_diff:.4f}"
|
| 142 |
+
return {"test":"Upsampling Stride-2","norm_diff":round(norm_diff,4),"score":s,"note":n}
|
| 143 |
+
|
| 144 |
+
def m10_patch_diversity(img):
|
| 145 |
+
gray=_g(img); h,w=gray.shape; ps=32
|
| 146 |
+
hc,wc=(h//ps)*ps,(w//ps)*ps; gray=gray[:hc,:wc]
|
| 147 |
+
patches=[]
|
| 148 |
+
for i in range(0,hc,ps):
|
| 149 |
+
for j in range(0,wc,ps):
|
| 150 |
+
patches.append(gray[i:i+ps,j:j+ps].ravel())
|
| 151 |
+
if len(patches)<4: return {"test":"Patch Diversity","score":0.0,"note":"Too few patches"}
|
| 152 |
+
patches=np.array(patches); means=np.mean(patches,axis=1); stds=np.std(patches,axis=1)
|
| 153 |
+
diversity=float(np.std(stds)/(np.mean(stds)+1e-9))
|
| 154 |
+
if diversity>0.5: s,n=-0.2,f"High patch diversity ({diversity:.3f}) β natural"
|
| 155 |
+
elif diversity<0.15: s,n=0.3,f"Low patch diversity ({diversity:.3f}) β GAN mode collapse"
|
| 156 |
+
else: s,n=0.0,f"Patch diversity={diversity:.3f}"
|
| 157 |
+
return {"test":"Patch Diversity","diversity":round(diversity,4),"score":s,"note":n}
|
| 158 |
+
|
| 159 |
+
def m11_color_consistency(img):
|
| 160 |
+
rgb=np.array(img.convert("RGB")).astype(np.float64); h,w,_=rgb.shape; ps=64
|
| 161 |
+
hc,wc=(h//ps)*ps,(w//ps)*ps; rgb=rgb[:hc,:wc]
|
| 162 |
+
ratios=[]
|
| 163 |
+
for i in range(0,hc,ps):
|
| 164 |
+
for j in range(0,wc,ps):
|
| 165 |
+
p=rgb[i:i+ps,j:j+ps]; m=np.mean(p,axis=(0,1))
|
| 166 |
+
if m[1]>10: ratios.append(m[0]/(m[1]+1e-9))
|
| 167 |
+
if len(ratios)<4: return {"test":"Color Ratio Consistency","score":0.0,"note":"Few patches"}
|
| 168 |
+
cv=float(np.std(ratios))/(float(np.mean(ratios))+1e-9)
|
| 169 |
+
if cv>0.1: s,n=-0.2,f"Varied color ratios (CV={cv:.3f})"
|
| 170 |
+
elif cv<0.02: s,n=0.2,f"Suspiciously uniform color ({cv:.3f})"
|
| 171 |
+
else: s,n=0.0,f"Color CV={cv:.3f}"
|
| 172 |
+
return {"test":"Color Ratio Consistency","cv":round(cv,4),"score":s,"note":n}
|
| 173 |
+
|
| 174 |
+
def m12_spectral_rolloff_shape(img):
|
| 175 |
+
gray=_g(img); fft=np.abs(np.fft.fftshift(np.fft.fft2(gray)))
|
| 176 |
+
h,w=fft.shape; cy,cx=h//2,w//2
|
| 177 |
+
diag1=np.array([fft[cy+i,cx+i] for i in range(min(cy,cx)//2)])
|
| 178 |
+
diag2=np.array([fft[cy+i,cx-i] for i in range(min(cy,cx)//2)])
|
| 179 |
+
if len(diag1)>5:
|
| 180 |
+
d1=np.log(diag1+1); d2=np.log(diag2+1)
|
| 181 |
+
aniso=float(np.mean(np.abs(d1-d2)))/(float(np.mean(d1))+1e-9)
|
| 182 |
+
else: aniso=0
|
| 183 |
+
if aniso>0.1: s,n=-0.1,f"Anisotropic rolloff ({aniso:.3f})"
|
| 184 |
+
elif aniso<0.02: s,n=0.2,f"Isotropic rolloff ({aniso:.3f}) β AI-like"
|
| 185 |
+
else: s,n=0.0,f"Rolloff anisotropy={aniso:.3f}"
|
| 186 |
+
return {"test":"Spectral Rolloff Shape","anisotropy":round(aniso,4),"score":s,"note":n}
|
| 187 |
+
|
| 188 |
+
def m13_texture_repetition(img):
|
| 189 |
+
gray=_g(img); h,w=gray.shape; ps=64
|
| 190 |
+
if h<ps*3 or w<ps*3: return {"test":"Texture Repetition","score":0.0,"note":"Too small"}
|
| 191 |
+
hc,wc=(h//ps)*ps,(w//ps)*ps; gray=gray[:hc,:wc]
|
| 192 |
+
patches=[]
|
| 193 |
+
for i in range(0,hc,ps):
|
| 194 |
+
for j in range(0,wc,ps):
|
| 195 |
+
p=gray[i:i+ps,j:j+ps]; p=(p-np.mean(p))/(np.std(p)+1e-9)
|
| 196 |
+
patches.append(p.ravel())
|
| 197 |
+
if len(patches)<4: return {"test":"Texture Repetition","score":0.0,"note":"Few patches"}
|
| 198 |
+
patches=np.array(patches)
|
| 199 |
+
# Find max correlation between non-adjacent patches
|
| 200 |
+
max_corr=0
|
| 201 |
+
for i in range(min(len(patches),20)):
|
| 202 |
+
for j in range(i+2,min(len(patches),20)):
|
| 203 |
+
c=float(np.corrcoef(patches[i],patches[j])[0,1])
|
| 204 |
+
if c>max_corr: max_corr=c
|
| 205 |
+
if max_corr>0.8: s,n=0.4,f"Repeated textures ({max_corr:.3f}) β GAN copy"
|
| 206 |
+
elif max_corr>0.5: s,n=0.2,f"Similar textures ({max_corr:.3f})"
|
| 207 |
+
else: s,n=-0.1,f"Varied textures ({max_corr:.3f})"
|
| 208 |
+
return {"test":"Texture Repetition","max_corr":round(max_corr,4),"score":s,"note":n}
|
| 209 |
+
|
| 210 |
+
def m14_highfreq_noise_structure(img):
|
| 211 |
+
gray=_g(img); noise=gray-gaussian_filter(gray,1.0)
|
| 212 |
+
fft=np.abs(np.fft.fftshift(np.fft.fft2(noise))); h,w=fft.shape; cy,cx=h//2,w//2
|
| 213 |
+
# Radial power in HF noise
|
| 214 |
+
Y,X=np.mgrid[0:h,0:w]; R=np.sqrt((X-cx)**2+(Y-cy)**2)
|
| 215 |
+
Rm=min(cy,cx); hf=fft[R>Rm*0.5]; lf=fft[R<Rm*0.3]
|
| 216 |
+
ratio=float(np.mean(hf))/(float(np.mean(lf))+1e-9)
|
| 217 |
+
if ratio>2: s,n=-0.2,f"HF-dominant noise ({ratio:.2f}) β sensor"
|
| 218 |
+
elif ratio<0.5: s,n=0.3,f"LF-dominant noise ({ratio:.2f}) β AI smoothing"
|
| 219 |
+
else: s,n=0.0,f"Noise HF/LF={ratio:.2f}"
|
| 220 |
+
return {"test":"HF Noise Structure","ratio":round(ratio,3),"score":s,"note":n}
|
| 221 |
+
|
| 222 |
+
def m15_phase_coherence(img):
|
| 223 |
+
gray=_g(img); fft=np.fft.fft2(gray); phase=np.angle(fft)
|
| 224 |
+
h,w=phase.shape
|
| 225 |
+
# Natural images: smooth phase transitions
|
| 226 |
+
ph_dx=np.abs(np.diff(phase,axis=1)); ph_dy=np.abs(np.diff(phase,axis=0))
|
| 227 |
+
# Wrap-around correction
|
| 228 |
+
ph_dx[ph_dx>np.pi]=2*np.pi-ph_dx[ph_dx>np.pi]
|
| 229 |
+
ph_dy[ph_dy>np.pi]=2*np.pi-ph_dy[ph_dy>np.pi]
|
| 230 |
+
smoothness=float(np.mean(ph_dx)+np.mean(ph_dy))
|
| 231 |
+
if smoothness<2: s,n=-0.2,f"Coherent phase ({smoothness:.3f})"
|
| 232 |
+
elif smoothness>2.5: s,n=0.2,f"Incoherent phase ({smoothness:.3f})"
|
| 233 |
+
else: s,n=0.0,f"Phase coherence={smoothness:.3f}"
|
| 234 |
+
return {"test":"Phase Coherence","smoothness":round(smoothness,4),"score":s,"note":n}
|
| 235 |
+
|
| 236 |
+
ALL_TESTS=[m01_fft_grid_8x8,m02_fft_grid_16x16,m03_spectral_slope,m04_diffusion_notches,
|
| 237 |
+
m05_autocorrelation,m06_checkerboard,m07_vae_boundaries,m08_spectral_symmetry,
|
| 238 |
+
m09_upsampling_stride,m10_patch_diversity,m11_color_consistency,m12_spectral_rolloff_shape,
|
| 239 |
+
m13_texture_repetition,m14_highfreq_noise_structure,m15_phase_coherence]
|
| 240 |
+
|
| 241 |
+
def run_model_agent(img):
|
| 242 |
+
findings,scores=[],[]
|
| 243 |
+
for fn in ALL_TESTS:
|
| 244 |
+
try: r=fn(img); findings.append(r); scores.append(r["score"])
|
| 245 |
+
except Exception as e: findings.append({"test":fn.__name__,"error":str(e),"score":0})
|
| 246 |
+
avg=float(np.mean(scores)) if scores else 0.0; conf=min(1.0,0.5+0.5*abs(avg))
|
| 247 |
+
viol=[f["test"] for f in findings if f.get("score",0)>0.2]
|
| 248 |
+
comp=[f["test"] for f in findings if f.get("score",0)<-0.1]
|
| 249 |
+
rat=f"Model signatures: {', '.join(viol)}." if viol else f"No artifacts: {', '.join(comp)}." if comp else "Model analysis inconclusive."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
for f in findings:
|
| 251 |
+
if f.get("note"): rat+=f" [{f['test']}]: {f['note']}."
|
| 252 |
+
return AgentEvidence("Generative Model Agent",np.clip(avg,-1,1),conf,max(0,1-len(scores)/len(ALL_TESTS)),rat,findings)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|