Upload agents/metadata_agent.py with huggingface_hub
Browse files- agents/metadata_agent.py +173 -438
agents/metadata_agent.py
CHANGED
|
@@ -1,444 +1,179 @@
|
|
| 1 |
-
"""
|
| 2 |
-
|
| 3 |
-
Analyzes file metadata and compression:
|
| 4 |
-
- EXIF validation (completeness and physical plausibility)
|
| 5 |
-
- Compression history (Error Level Analysis for double JPEG)
|
| 6 |
-
- AI metadata traces (XMP/IPTC parser for generator signatures)
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import numpy as np
|
| 10 |
from PIL import Image, ImageChops, ImageEnhance
|
| 11 |
-
from PIL.ExifTags import TAGS
|
| 12 |
-
import
|
| 13 |
-
import
|
| 14 |
-
from typing import Dict, Any, List, Tuple
|
| 15 |
-
|
| 16 |
from agents.optical_agent import AgentEvidence
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
try:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
# Camera info
|
| 42 |
-
has_make = "Make" in decoded
|
| 43 |
-
has_model = "Model" in decoded
|
| 44 |
-
has_lens = "LensModel" in decoded or "LensInfo" in decoded
|
| 45 |
-
has_focal = "FocalLength" in decoded
|
| 46 |
-
has_exposure = "ExposureTime" in decoded
|
| 47 |
-
has_iso = "ISOSpeedRatings" in decoded
|
| 48 |
-
has_aperture = "FNumber" in decoded
|
| 49 |
-
has_datetime = "DateTime" in decoded or "DateTimeOriginal" in decoded
|
| 50 |
-
has_gps = "GPSInfo" in decoded
|
| 51 |
-
has_software = "Software" in decoded
|
| 52 |
-
|
| 53 |
-
camera_fields = sum([has_make, has_model, has_lens, has_focal,
|
| 54 |
-
has_exposure, has_iso, has_aperture])
|
| 55 |
-
|
| 56 |
-
if camera_fields == 0:
|
| 57 |
-
suspicious_flags.append("No camera metadata (stripped or AI-generated)")
|
| 58 |
-
elif camera_fields >= 4:
|
| 59 |
-
authenticity_markers.append(f"Rich camera metadata ({camera_fields}/7 fields)")
|
| 60 |
-
|
| 61 |
-
if not decoded:
|
| 62 |
-
suspicious_flags.append("Completely empty EXIF (strong AI indicator)")
|
| 63 |
-
|
| 64 |
-
if has_software:
|
| 65 |
-
sw = decoded.get("Software", "").lower()
|
| 66 |
-
ai_keywords = ["stable diffusion", "midjourney", "dall-e", "comfyui",
|
| 67 |
-
"automatic1111", "invoke", "flux", "sd", "novelai"]
|
| 68 |
-
edit_keywords = ["photoshop", "gimp", "lightroom", "capture one"]
|
| 69 |
-
if any(k in sw for k in ai_keywords):
|
| 70 |
-
suspicious_flags.append(f"AI generation software: {decoded['Software']}")
|
| 71 |
-
elif any(k in sw for k in edit_keywords):
|
| 72 |
-
suspicious_flags.append(f"Editing software detected: {decoded['Software']}")
|
| 73 |
-
else:
|
| 74 |
-
authenticity_markers.append(f"Software: {decoded['Software']}")
|
| 75 |
-
|
| 76 |
-
if has_datetime:
|
| 77 |
-
authenticity_markers.append("Timestamp present")
|
| 78 |
-
|
| 79 |
-
if has_gps:
|
| 80 |
-
authenticity_markers.append("GPS coordinates present (strong authenticity marker)")
|
| 81 |
-
|
| 82 |
-
# Physical plausibility checks
|
| 83 |
-
if has_focal and has_aperture:
|
| 84 |
-
try:
|
| 85 |
-
focal = float(str(decoded.get("FocalLength", "0")).split("/")[0])
|
| 86 |
-
fnumber = float(str(decoded.get("FNumber", "0")).split("/")[0])
|
| 87 |
-
if focal > 0 and fnumber > 0:
|
| 88 |
-
# Check if aperture is physically possible for focal length
|
| 89 |
-
if fnumber < 0.7 or fnumber > 64:
|
| 90 |
-
suspicious_flags.append(f"Impossible aperture: f/{fnumber}")
|
| 91 |
-
else:
|
| 92 |
-
authenticity_markers.append(f"Plausible optics: {focal}mm f/{fnumber}")
|
| 93 |
-
except Exception:
|
| 94 |
-
pass
|
| 95 |
-
|
| 96 |
-
# Score
|
| 97 |
-
n_suspicious = len(suspicious_flags)
|
| 98 |
-
n_authentic = len(authenticity_markers)
|
| 99 |
-
|
| 100 |
-
if n_suspicious == 0 and n_authentic >= 3:
|
| 101 |
-
score = -0.5
|
| 102 |
-
note = "Rich, plausible EXIF metadata (strong authenticity)"
|
| 103 |
-
elif n_suspicious >= 2 or (not decoded):
|
| 104 |
-
score = 0.5
|
| 105 |
-
note = "Missing or suspicious metadata"
|
| 106 |
-
elif n_suspicious == 1:
|
| 107 |
-
score = 0.2
|
| 108 |
-
note = "Minor metadata concern"
|
| 109 |
-
else:
|
| 110 |
-
score = -0.1
|
| 111 |
-
note = "Partial metadata present"
|
| 112 |
-
|
| 113 |
-
return {
|
| 114 |
-
"test": "EXIF Validation",
|
| 115 |
-
"total_fields": len(decoded),
|
| 116 |
-
"camera_fields": camera_fields,
|
| 117 |
-
"suspicious_flags": suspicious_flags,
|
| 118 |
-
"authenticity_markers": authenticity_markers,
|
| 119 |
-
"exif_data": decoded,
|
| 120 |
-
"score": score,
|
| 121 |
-
"note": note,
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
# βββ Error Level Analysis (ELA) βββββββββββββββββββββββββββββββββββββ
|
| 126 |
-
def analyze_ela(img: Image.Image, quality: int = 90) -> Dict[str, Any]:
|
| 127 |
-
"""
|
| 128 |
-
Re-save at known JPEG quality and compute pixel-level differences.
|
| 129 |
-
Manipulated regions show different error levels than unmodified areas.
|
| 130 |
-
Also detects double JPEG compression.
|
| 131 |
-
"""
|
| 132 |
-
# Resave at target quality
|
| 133 |
-
buf = io.BytesIO()
|
| 134 |
-
img_rgb = img.convert("RGB")
|
| 135 |
-
img_rgb.save(buf, "JPEG", quality=quality)
|
| 136 |
-
buf.seek(0)
|
| 137 |
-
resaved = Image.open(buf).convert("RGB")
|
| 138 |
-
|
| 139 |
-
# Pixel difference
|
| 140 |
-
ela_img = ImageChops.difference(img_rgb, resaved)
|
| 141 |
-
|
| 142 |
-
# Scale for visibility
|
| 143 |
-
extrema = ela_img.getextrema()
|
| 144 |
-
max_diff = max([e[1] for e in extrema]) or 1
|
| 145 |
-
scale = 255.0 / max_diff
|
| 146 |
-
ela_visible = ImageEnhance.Brightness(ela_img).enhance(scale)
|
| 147 |
-
|
| 148 |
-
ela_arr = np.array(ela_img).astype(np.float64)
|
| 149 |
-
|
| 150 |
-
# Global statistics
|
| 151 |
-
global_mean = float(np.mean(ela_arr))
|
| 152 |
-
global_std = float(np.std(ela_arr))
|
| 153 |
-
|
| 154 |
-
# Block-level analysis (detect inconsistent compression)
|
| 155 |
-
block_means = []
|
| 156 |
-
h, w, _ = ela_arr.shape
|
| 157 |
-
bs = 32
|
| 158 |
-
for i in range(0, h - bs, bs):
|
| 159 |
-
for j in range(0, w - bs, bs):
|
| 160 |
-
block = ela_arr[i:i + bs, j:j + bs, :]
|
| 161 |
-
block_means.append(float(np.mean(block)))
|
| 162 |
-
|
| 163 |
-
block_means = np.array(block_means)
|
| 164 |
-
block_std = float(np.std(block_means))
|
| 165 |
-
block_range = float(np.max(block_means) - np.min(block_means))
|
| 166 |
-
|
| 167 |
-
# High block variance = inconsistent compression = manipulation
|
| 168 |
-
if block_std > 8.0 and block_range > 30:
|
| 169 |
-
score = 0.6
|
| 170 |
-
note = f"High ELA variance (Ο={block_std:.1f}, range={block_range:.1f}) β manipulation regions detected"
|
| 171 |
-
elif block_std > 4.0:
|
| 172 |
-
score = 0.3
|
| 173 |
-
note = f"Moderate ELA variance (Ο={block_std:.1f}) β possible manipulation"
|
| 174 |
-
elif global_std < 1.0:
|
| 175 |
-
score = 0.2
|
| 176 |
-
note = "Unusually uniform ELA (possible AI generation with no JPEG history)"
|
| 177 |
-
else:
|
| 178 |
-
score = -0.2
|
| 179 |
-
note = f"Consistent ELA levels (Ο={block_std:.1f}, natural compression)"
|
| 180 |
-
|
| 181 |
-
return {
|
| 182 |
-
"test": "Error Level Analysis",
|
| 183 |
-
"global_mean": round(global_mean, 4),
|
| 184 |
-
"global_std": round(global_std, 4),
|
| 185 |
-
"block_std": round(block_std, 4),
|
| 186 |
-
"block_range": round(block_range, 4),
|
| 187 |
-
"score": score,
|
| 188 |
-
"note": note,
|
| 189 |
-
"ela_image": ela_visible,
|
| 190 |
-
}
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
# βββ AI Metadata Traces ββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββ
|
| 194 |
-
def analyze_ai_metadata(img: Image.Image) -> Dict[str, Any]:
|
| 195 |
-
"""
|
| 196 |
-
Check for AI generation markers in XMP, IPTC, and other metadata.
|
| 197 |
-
C2PA, Content Credentials, and generator watermarks.
|
| 198 |
-
"""
|
| 199 |
-
info = img.info or {}
|
| 200 |
-
suspicious_flags = []
|
| 201 |
-
found_traces = []
|
| 202 |
-
|
| 203 |
-
# Check PNG text chunks
|
| 204 |
-
for key in info:
|
| 205 |
-
key_lower = str(key).lower()
|
| 206 |
-
val = str(info[key])[:500]
|
| 207 |
-
|
| 208 |
-
ai_markers = ["stable diffusion", "comfyui", "automatic1111",
|
| 209 |
-
"midjourney", "dall-e", "novelai", "invoke",
|
| 210 |
-
"parameters", "prompt", "negative_prompt",
|
| 211 |
-
"steps", "sampler", "cfg_scale", "model",
|
| 212 |
-
"flux", "sd_model", "clip_skip"]
|
| 213 |
-
|
| 214 |
-
if any(m in key_lower or m in val.lower() for m in ai_markers):
|
| 215 |
-
found_traces.append(f"{key}: {val[:100]}")
|
| 216 |
-
|
| 217 |
-
# Check for XMP data
|
| 218 |
-
xmp_data = info.get("XML:com.adobe.xmp", "") or info.get("xmp", "")
|
| 219 |
-
if isinstance(xmp_data, bytes):
|
| 220 |
-
xmp_data = xmp_data.decode("utf-8", errors="ignore")
|
| 221 |
-
|
| 222 |
-
if "ai:" in xmp_data.lower() or "generativeAI" in xmp_data:
|
| 223 |
-
found_traces.append("XMP contains AI generation markers")
|
| 224 |
-
|
| 225 |
-
if "c2pa" in xmp_data.lower() or "contentcredentials" in xmp_data.lower():
|
| 226 |
-
found_traces.append("Content Credentials (C2PA) detected")
|
| 227 |
-
|
| 228 |
-
if found_traces:
|
| 229 |
-
score = 0.8
|
| 230 |
-
note = f"AI generation metadata found: {'; '.join(found_traces[:3])}"
|
| 231 |
-
else:
|
| 232 |
-
score = 0.0
|
| 233 |
-
note = "No AI metadata traces detected"
|
| 234 |
-
|
| 235 |
-
return {
|
| 236 |
-
"test": "AI Metadata Traces",
|
| 237 |
-
"traces_found": found_traces,
|
| 238 |
-
"info_keys": list(str(k) for k in info.keys())[:20],
|
| 239 |
-
"score": score,
|
| 240 |
-
"note": note,
|
| 241 |
-
}
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
# βββ Thumbnail Consistency βββββββββββββββββββββββββββββββββββββββββββ
|
| 245 |
-
def analyze_thumbnail_consistency(img: Image.Image) -> Dict[str, Any]:
|
| 246 |
-
"""
|
| 247 |
-
JPEG files often embed a thumbnail. If the main image was manipulated
|
| 248 |
-
but the thumbnail wasn't updated, they'll differ.
|
| 249 |
-
"""
|
| 250 |
-
try:
|
| 251 |
-
exif_data = img._getexif() or {}
|
| 252 |
-
except Exception:
|
| 253 |
-
exif_data = {}
|
| 254 |
-
|
| 255 |
-
# Check for embedded thumbnail
|
| 256 |
-
has_thumbnail = False
|
| 257 |
-
try:
|
| 258 |
-
if hasattr(img, 'applist'):
|
| 259 |
-
for app in img.applist:
|
| 260 |
-
if b'thumbnail' in app[1].lower() if isinstance(app[1], bytes) else False:
|
| 261 |
-
has_thumbnail = True
|
| 262 |
-
except Exception:
|
| 263 |
-
pass
|
| 264 |
-
|
| 265 |
-
# Check EXIF thumbnail tag (tag 513 = JPEGInterchangeFormat)
|
| 266 |
-
if 513 in exif_data or 514 in exif_data:
|
| 267 |
-
has_thumbnail = True
|
| 268 |
-
|
| 269 |
-
if not has_thumbnail:
|
| 270 |
-
return {
|
| 271 |
-
"test": "Thumbnail Consistency",
|
| 272 |
-
"score": 0.0,
|
| 273 |
-
"note": "No embedded thumbnail found for comparison",
|
| 274 |
-
}
|
| 275 |
-
|
| 276 |
-
return {
|
| 277 |
-
"test": "Thumbnail Consistency",
|
| 278 |
-
"has_thumbnail": True,
|
| 279 |
-
"score": -0.1,
|
| 280 |
-
"note": "Embedded thumbnail present (consistent with real camera output)",
|
| 281 |
-
}
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
# βββ Watermark Detection ββββββββββββββββββββββββββββββββββββββββββββ
|
| 285 |
-
def analyze_watermarks(img: Image.Image) -> Dict[str, Any]:
|
| 286 |
-
"""
|
| 287 |
-
Detect invisible watermarks (frequency domain) and visible watermarks.
|
| 288 |
-
Some AI generators embed identifying watermarks.
|
| 289 |
-
"""
|
| 290 |
-
gray = np.array(img.convert("L")).astype(np.float64)
|
| 291 |
-
|
| 292 |
-
# Check for periodic watermark patterns in FFT
|
| 293 |
-
fft = np.fft.fft2(gray)
|
| 294 |
-
fft_shift = np.fft.fftshift(fft)
|
| 295 |
-
magnitude = np.log(np.abs(fft_shift) + 1)
|
| 296 |
-
|
| 297 |
-
h, w = magnitude.shape
|
| 298 |
-
cy, cx = h // 2, w // 2
|
| 299 |
-
|
| 300 |
-
# Remove DC component and check for suspicious isolated peaks
|
| 301 |
-
magnitude_clean = magnitude.copy()
|
| 302 |
-
magnitude_clean[cy - 3:cy + 3, cx - 3:cx + 3] = 0
|
| 303 |
-
|
| 304 |
-
# Find isolated bright spots (potential watermark carriers)
|
| 305 |
-
from scipy.ndimage import maximum_filter
|
| 306 |
-
local_max = maximum_filter(magnitude_clean, size=10)
|
| 307 |
-
peaks = (magnitude_clean == local_max) & (magnitude_clean > np.percentile(magnitude_clean, 99.5))
|
| 308 |
-
n_isolated_peaks = int(np.sum(peaks))
|
| 309 |
-
|
| 310 |
-
# Check image info for C2PA / Content Credentials
|
| 311 |
-
info = img.info or {}
|
| 312 |
-
c2pa_found = False
|
| 313 |
-
for key in info:
|
| 314 |
-
key_str = str(key).lower()
|
| 315 |
-
val_str = str(info[key])[:500].lower()
|
| 316 |
-
if any(marker in key_str or marker in val_str
|
| 317 |
-
for marker in ["c2pa", "contentcredentials", "content_authenticity"]):
|
| 318 |
-
c2pa_found = True
|
| 319 |
-
|
| 320 |
-
if c2pa_found:
|
| 321 |
-
score = 0.0
|
| 322 |
-
note = "C2PA Content Credentials watermark detected (provenance tracking)"
|
| 323 |
-
elif n_isolated_peaks > 20:
|
| 324 |
-
score = 0.2
|
| 325 |
-
note = f"Suspicious frequency-domain peaks ({n_isolated_peaks}, possible embedded watermark)"
|
| 326 |
-
else:
|
| 327 |
-
score = 0.0
|
| 328 |
-
note = f"No watermark signatures detected ({n_isolated_peaks} peaks)"
|
| 329 |
-
|
| 330 |
-
return {
|
| 331 |
-
"test": "Watermark Detection",
|
| 332 |
-
"isolated_peaks": n_isolated_peaks,
|
| 333 |
-
"c2pa_found": c2pa_found,
|
| 334 |
-
"score": score,
|
| 335 |
-
"note": note,
|
| 336 |
-
}
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
# βββ Compression Ghost Detection ββββββββββββββββββββββββββββββββββββ
|
| 340 |
-
def analyze_compression_ghosts(img: Image.Image) -> Dict[str, Any]:
|
| 341 |
-
"""
|
| 342 |
-
Double JPEG compression leaves 'ghosts' β periodic artifacts at
|
| 343 |
-
block boundaries that differ from single compression.
|
| 344 |
-
Detect by analyzing 8Γ8 block boundary discontinuities.
|
| 345 |
-
"""
|
| 346 |
-
gray = np.array(img.convert("L")).astype(np.float64)
|
| 347 |
-
h, w = gray.shape
|
| 348 |
-
h_crop, w_crop = (h // 8) * 8, (w // 8) * 8
|
| 349 |
-
gray = gray[:h_crop, :w_crop]
|
| 350 |
-
|
| 351 |
-
# Measure discontinuity at 8Γ8 block boundaries
|
| 352 |
-
boundary_diffs = []
|
| 353 |
-
interior_diffs = []
|
| 354 |
-
|
| 355 |
-
for i in range(1, h_crop):
|
| 356 |
-
if i % 8 == 0:
|
| 357 |
-
# Block boundary row
|
| 358 |
-
boundary_diffs.extend(np.abs(gray[i, :] - gray[i - 1, :]).tolist())
|
| 359 |
-
else:
|
| 360 |
-
interior_diffs.extend(np.abs(gray[i, :] - gray[i - 1, :]).tolist())
|
| 361 |
-
|
| 362 |
-
for j in range(1, w_crop):
|
| 363 |
-
if j % 8 == 0:
|
| 364 |
-
boundary_diffs.extend(np.abs(gray[:, j] - gray[:, j - 1]).tolist())
|
| 365 |
-
else:
|
| 366 |
-
interior_diffs.extend(np.abs(gray[:, j] - gray[:, j - 1]).tolist())
|
| 367 |
-
|
| 368 |
-
if boundary_diffs and interior_diffs:
|
| 369 |
-
boundary_mean = float(np.mean(boundary_diffs))
|
| 370 |
-
interior_mean = float(np.mean(interior_diffs))
|
| 371 |
-
blockiness = boundary_mean / (interior_mean + 1e-9)
|
| 372 |
-
else:
|
| 373 |
-
blockiness = 1.0
|
| 374 |
-
|
| 375 |
-
# Blockiness > 1.2 suggests JPEG compression; > 1.5 suggests double compression
|
| 376 |
-
if blockiness > 1.5:
|
| 377 |
-
score = 0.3
|
| 378 |
-
note = f"Strong block boundary artifacts (blockiness={blockiness:.3f}, possible double JPEG)"
|
| 379 |
-
elif blockiness > 1.2:
|
| 380 |
-
score = -0.1
|
| 381 |
-
note = f"Normal JPEG blockiness ({blockiness:.3f})"
|
| 382 |
-
elif blockiness < 1.02:
|
| 383 |
-
score = 0.1
|
| 384 |
-
note = f"No block boundaries (blockiness={blockiness:.3f}, non-JPEG or AI)"
|
| 385 |
-
else:
|
| 386 |
-
score = 0.0
|
| 387 |
-
note = f"Mild blockiness ({blockiness:.3f})"
|
| 388 |
-
|
| 389 |
-
return {
|
| 390 |
-
"test": "Compression Ghost Detection",
|
| 391 |
-
"blockiness_ratio": round(blockiness, 4),
|
| 392 |
-
"score": score,
|
| 393 |
-
"note": note,
|
| 394 |
-
}
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
# βββ Main Agent Entry Point βββββββββββββββββββββββββββββββββββββββββ
|
| 398 |
-
def run_metadata_agent(img: Image.Image) -> AgentEvidence:
|
| 399 |
-
"""Run all metadata analysis tests."""
|
| 400 |
-
findings = []
|
| 401 |
-
scores = []
|
| 402 |
-
|
| 403 |
-
for fn in [analyze_exif, analyze_ela, analyze_ai_metadata,
|
| 404 |
-
analyze_thumbnail_consistency, analyze_watermarks, analyze_compression_ghosts]:
|
| 405 |
-
try:
|
| 406 |
-
result = fn(img)
|
| 407 |
-
findings.append(result)
|
| 408 |
-
scores.append(result["score"])
|
| 409 |
-
except Exception as e:
|
| 410 |
-
findings.append({"test": fn.__name__, "error": str(e), "score": 0})
|
| 411 |
-
|
| 412 |
-
avg_score = float(np.mean(scores)) if scores else 0.0
|
| 413 |
-
confidence = min(1.0, 0.5 + 0.5 * abs(avg_score))
|
| 414 |
-
|
| 415 |
-
violations = [f["test"] for f in findings if f.get("score", 0) > 0.2]
|
| 416 |
-
compliant = [f["test"] for f in findings if f.get("score", 0) < -0.1]
|
| 417 |
-
|
| 418 |
-
if violations:
|
| 419 |
-
rationale = f"Metadata violations: {', '.join(violations)}."
|
| 420 |
-
elif compliant:
|
| 421 |
-
rationale = f"Metadata consistent: {', '.join(compliant)}."
|
| 422 |
-
else:
|
| 423 |
-
rationale = "Metadata analysis inconclusive."
|
| 424 |
-
|
| 425 |
-
for f in findings:
|
| 426 |
-
if f.get("note"):
|
| 427 |
-
rationale += f" [{f['test']}]: {f['note']}."
|
| 428 |
-
|
| 429 |
-
# Extract ELA image if available
|
| 430 |
-
ela_img = None
|
| 431 |
for f in findings:
|
| 432 |
-
if "
|
| 433 |
-
|
| 434 |
-
del f["ela_image"] # Don't include in serializable findings
|
| 435 |
-
|
| 436 |
-
return AgentEvidence(
|
| 437 |
-
agent_name="Metadata Agent",
|
| 438 |
-
violation_score=np.clip(avg_score, -1, 1),
|
| 439 |
-
confidence=confidence,
|
| 440 |
-
failure_prob=max(0.0, 1.0 - len(scores) / 6),
|
| 441 |
-
rationale=rationale,
|
| 442 |
-
sub_findings=findings,
|
| 443 |
-
visual_evidence=ela_img,
|
| 444 |
-
)
|
|
|
|
| 1 |
+
"""FORENSIQ β Metadata Agent (12 features)"""
|
| 2 |
+
import numpy as np, io
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from PIL import Image, ImageChops, ImageEnhance
|
| 4 |
+
from PIL.ExifTags import TAGS
|
| 5 |
+
from scipy.ndimage import maximum_filter, gaussian_filter
|
| 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 d01_exif_completeness(img):
|
| 12 |
+
try: exif=img._getexif() or {}
|
| 13 |
+
except: exif={}
|
| 14 |
+
decoded={}
|
| 15 |
+
for tid,v in exif.items():
|
| 16 |
+
t=TAGS.get(tid,str(tid))
|
| 17 |
+
try: decoded[t]=str(v)[:200]
|
| 18 |
+
except: decoded[t]="<binary>"
|
| 19 |
+
flags,auth=[],[]
|
| 20 |
+
has_make="Make" in decoded; has_model="Model" in decoded; has_lens="LensModel" in decoded or "LensInfo" in decoded
|
| 21 |
+
has_focal="FocalLength" in decoded; has_exp="ExposureTime" in decoded; has_iso="ISOSpeedRatings" in decoded
|
| 22 |
+
has_f="FNumber" in decoded; cam=sum([has_make,has_model,has_lens,has_focal,has_exp,has_iso,has_f])
|
| 23 |
+
if cam==0: flags.append("No camera metadata")
|
| 24 |
+
elif cam>=4: auth.append(f"Rich EXIF ({cam}/7)")
|
| 25 |
+
if not decoded: flags.append("Empty EXIF")
|
| 26 |
+
if "GPSInfo" in decoded: auth.append("GPS present")
|
| 27 |
+
if cam>=4 and not flags: s,n=-0.5,f"Rich plausible EXIF ({cam}/7 fields)"
|
| 28 |
+
elif not decoded or len(flags)>=2: s,n=0.5,"Missing/suspicious metadata"
|
| 29 |
+
elif flags: s,n=0.2,"Minor metadata concern"
|
| 30 |
+
else: s,n=-0.1,"Partial metadata"
|
| 31 |
+
return {"test":"EXIF Completeness","fields":len(decoded),"camera_fields":cam,"exif_data":decoded,"score":s,"note":n}
|
| 32 |
+
|
| 33 |
+
def d02_software_check(img):
|
| 34 |
+
try: exif=img._getexif() or {}
|
| 35 |
+
except: exif={}
|
| 36 |
+
decoded={TAGS.get(tid,str(tid)):str(v)[:200] for tid,v in exif.items()}
|
| 37 |
+
sw=decoded.get("Software","").lower()
|
| 38 |
+
ai=["stable diffusion","midjourney","dall-e","comfyui","automatic1111","invoke","flux","novelai","sd"]
|
| 39 |
+
edit=["photoshop","gimp","lightroom","capture one","snapseed"]
|
| 40 |
+
if any(k in sw for k in ai): s,n=0.8,f"AI software: {decoded.get('Software','')}"
|
| 41 |
+
elif any(k in sw for k in edit): s,n=0.2,f"Editing software: {decoded.get('Software','')}"
|
| 42 |
+
elif sw: s,n=-0.1,f"Software: {decoded.get('Software','')}"
|
| 43 |
+
else: s,n=0.1,"No software tag"
|
| 44 |
+
return {"test":"Software Detection","score":s,"note":n}
|
| 45 |
+
|
| 46 |
+
def d03_ela(img, quality=90):
|
| 47 |
+
buf=io.BytesIO(); img_rgb=img.convert("RGB"); img_rgb.save(buf,"JPEG",quality=quality); buf.seek(0)
|
| 48 |
+
resaved=Image.open(buf).convert("RGB"); ela=ImageChops.difference(img_rgb,resaved)
|
| 49 |
+
ext=ela.getextrema(); mx=max(e[1] for e in ext) or 1
|
| 50 |
+
ela_vis=ImageEnhance.Brightness(ela).enhance(255.0/mx)
|
| 51 |
+
ea=np.array(ela).astype(float); bs=32; bm=[]
|
| 52 |
+
h,w,_=ea.shape
|
| 53 |
+
for i in range(0,h-bs,bs):
|
| 54 |
+
for j in range(0,w-bs,bs): bm.append(float(np.mean(ea[i:i+bs,j:j+bs])))
|
| 55 |
+
bm=np.array(bm); bstd=float(np.std(bm)); br=float(np.max(bm)-np.min(bm))
|
| 56 |
+
if bstd>8 and br>30: s,n=0.6,f"High ELA variance (Ο={bstd:.1f}) β manipulation"
|
| 57 |
+
elif bstd>4: s,n=0.3,f"Moderate ELA (Ο={bstd:.1f})"
|
| 58 |
+
elif float(np.std(ea))<1: s,n=0.2,"Uniform ELA β AI"
|
| 59 |
+
else: s,n=-0.2,f"Consistent ELA (Ο={bstd:.1f})"
|
| 60 |
+
return {"test":"Error Level Analysis","block_std":round(bstd,3),"score":s,"note":n,"ela_image":ela_vis}
|
| 61 |
+
|
| 62 |
+
def d04_ai_metadata(img):
|
| 63 |
+
info=img.info or {}; traces=[]
|
| 64 |
+
markers=["stable diffusion","comfyui","automatic1111","midjourney","dall-e","novelai","parameters","prompt","negative_prompt","steps","sampler","cfg_scale","flux","sd_model"]
|
| 65 |
+
for k in info:
|
| 66 |
+
ks=str(k).lower(); vs=str(info[k])[:500].lower()
|
| 67 |
+
if any(m in ks or m in vs for m in markers): traces.append(f"{k}: {str(info[k])[:80]}")
|
| 68 |
+
xmp=str(info.get("XML:com.adobe.xmp","") or info.get("xmp",""))
|
| 69 |
+
if "generativeAI" in xmp or "ai:" in xmp.lower(): traces.append("XMP AI markers")
|
| 70 |
+
if "c2pa" in xmp.lower(): traces.append("C2PA Content Credentials")
|
| 71 |
+
if traces: s,n=0.8,f"AI traces: {'; '.join(traces[:3])}"
|
| 72 |
+
else: s,n=0.0,"No AI metadata"
|
| 73 |
+
return {"test":"AI Metadata Traces","traces":traces,"score":s,"note":n}
|
| 74 |
+
|
| 75 |
+
def d05_thumbnail(img):
|
| 76 |
+
try: exif=img._getexif() or {}
|
| 77 |
+
except: exif={}
|
| 78 |
+
has_thumb=513 in exif or 514 in exif
|
| 79 |
+
if has_thumb: s,n=-0.1,"Thumbnail present β camera"
|
| 80 |
+
else: s,n=0.0,"No thumbnail"
|
| 81 |
+
return {"test":"Thumbnail Check","has_thumbnail":has_thumb,"score":s,"note":n}
|
| 82 |
+
|
| 83 |
+
def d06_watermark(img):
|
| 84 |
+
gray=_g(img); fft=np.fft.fftshift(np.fft.fft2(gray)); mag=np.log(np.abs(fft)+1)
|
| 85 |
+
h,w=mag.shape; cy,cx=h//2,w//2; mc=mag.copy(); mc[cy-3:cy+3,cx-3:cx+3]=0
|
| 86 |
+
lm=maximum_filter(mc,10); peaks=(mc==lm)&(mc>np.percentile(mc,99.5))
|
| 87 |
+
np_=int(np.sum(peaks))
|
| 88 |
+
if np_>20: s,n=0.2,f"Frequency peaks ({np_}) β watermark?"
|
| 89 |
+
else: s,n=0.0,f"No watermark ({np_} peaks)"
|
| 90 |
+
return {"test":"Watermark Detection","peaks":np_,"score":s,"note":n}
|
| 91 |
+
|
| 92 |
+
def d07_compression_ghost(img):
|
| 93 |
+
gray=_g(img); h,w=gray.shape; hc,wc=(h//8)*8,(w//8)*8; gray=gray[:hc,:wc]
|
| 94 |
+
bd,it=[],[]
|
| 95 |
+
for i in range(1,hc):
|
| 96 |
+
rd=np.abs(gray[i,:]-gray[i-1,:])
|
| 97 |
+
if i%8==0: bd.extend(rd.tolist())
|
| 98 |
+
else: it.extend(rd.tolist())
|
| 99 |
+
bk=float(np.mean(bd))/(float(np.mean(it))+1e-9) if it else 1
|
| 100 |
+
if bk>1.5: s,n=0.3,f"Double JPEG (blockiness={bk:.3f})"
|
| 101 |
+
elif bk>1.2: s,n=-0.1,f"JPEG blocks ({bk:.3f})"
|
| 102 |
+
elif bk<1.02: s,n=0.1,f"No blocks ({bk:.3f})"
|
| 103 |
+
else: s,n=0.0,f"Blockiness={bk:.3f}"
|
| 104 |
+
return {"test":"Compression Ghosts","blockiness":round(bk,4),"score":s,"note":n}
|
| 105 |
+
|
| 106 |
+
def d08_icc_profile(img):
|
| 107 |
+
icc=img.info.get("icc_profile",None)
|
| 108 |
+
if icc:
|
| 109 |
+
size=len(icc)
|
| 110 |
+
if size>100: s,n=-0.2,f"ICC profile ({size}B) β camera/editor"
|
| 111 |
+
else: s,n=0.0,f"Small ICC ({size}B)"
|
| 112 |
+
else: s,n=0.1,"No ICC profile"
|
| 113 |
+
return {"test":"ICC Color Profile","has_icc":icc is not None,"score":s,"note":n}
|
| 114 |
+
|
| 115 |
+
def d09_color_space(img):
|
| 116 |
+
mode=img.mode
|
| 117 |
+
try: exif=img._getexif() or {}
|
| 118 |
+
except: exif={}
|
| 119 |
+
cs=str(exif.get(40961,"")) # ColorSpace tag
|
| 120 |
+
if cs=="1": s,n=-0.1,"sRGB color space β standard"
|
| 121 |
+
elif cs=="65535": s,n=-0.1,"Uncalibrated (wide gamut)"
|
| 122 |
+
elif mode=="CMYK": s,n=-0.2,"CMYK β professional source"
|
| 123 |
+
else: s,n=0.0,f"Color mode={mode}"
|
| 124 |
+
return {"test":"Color Space","mode":mode,"score":s,"note":n}
|
| 125 |
+
|
| 126 |
+
def d10_gps_plausibility(img):
|
| 127 |
+
try: exif=img._getexif() or {}
|
| 128 |
+
except: exif={}
|
| 129 |
+
gps=exif.get(34853)
|
| 130 |
+
if not gps: return {"test":"GPS Plausibility","score":0.0,"note":"No GPS data"}
|
| 131 |
try:
|
| 132 |
+
# Check if GPS coordinates are physically possible
|
| 133 |
+
lat_ref=gps.get(1,"N"); lon_ref=gps.get(3,"E")
|
| 134 |
+
lat=gps.get(2,(0,0,0)); lon=gps.get(4,(0,0,0))
|
| 135 |
+
# Simple validation: lat β [-90,90], lon β [-180,180]
|
| 136 |
+
s,n=-0.2,f"GPS present ({lat_ref}, {lon_ref})"
|
| 137 |
+
except: s,n=0.0,"GPS parse error"
|
| 138 |
+
return {"test":"GPS Plausibility","score":s,"note":n}
|
| 139 |
+
|
| 140 |
+
def d11_maker_note(img):
|
| 141 |
+
try: exif=img._getexif() or {}
|
| 142 |
+
except: exif={}
|
| 143 |
+
mn=exif.get(37500) # MakerNote tag
|
| 144 |
+
if mn:
|
| 145 |
+
size=len(mn) if isinstance(mn,bytes) else len(str(mn))
|
| 146 |
+
if size>100: s,n=-0.3,f"MakerNote ({size}B) β camera firmware"
|
| 147 |
+
else: s,n=-0.1,f"Small MakerNote ({size}B)"
|
| 148 |
+
else: s,n=0.1,"No MakerNote"
|
| 149 |
+
return {"test":"Maker Note","score":s,"note":n}
|
| 150 |
+
|
| 151 |
+
def d12_file_structure(img):
|
| 152 |
+
fmt=img.format or "unknown"; w,h=img.size
|
| 153 |
+
mp=w*h/1e6
|
| 154 |
+
standard_mp=[0.3,0.8,1,2,3,4,5,8,10,12,16,20,24,36,45,50,61,100,108,150,200]
|
| 155 |
+
closest=min(standard_mp,key=lambda x:abs(mp-x)); diff=abs(mp-closest)/closest if closest>0 else 1
|
| 156 |
+
if diff<0.05: s,n=-0.1,f"Standard resolution ({mp:.1f}MP β {closest}MP)"
|
| 157 |
+
elif diff>0.3: s,n=0.1,f"Non-standard resolution ({mp:.1f}MP)"
|
| 158 |
+
else: s,n=0.0,f"{mp:.1f}MP, format={fmt}"
|
| 159 |
+
return {"test":"File Structure","format":fmt,"megapixels":round(mp,2),"score":s,"note":n}
|
| 160 |
+
|
| 161 |
+
ALL_TESTS=[d01_exif_completeness,d02_software_check,d03_ela,d04_ai_metadata,d05_thumbnail,
|
| 162 |
+
d06_watermark,d07_compression_ghost,d08_icc_profile,d09_color_space,
|
| 163 |
+
d10_gps_plausibility,d11_maker_note,d12_file_structure]
|
| 164 |
+
|
| 165 |
+
def run_metadata_agent(img):
|
| 166 |
+
findings,scores=[],[]
|
| 167 |
+
ela_img=None
|
| 168 |
+
for fn in ALL_TESTS:
|
| 169 |
try:
|
| 170 |
+
r=fn(img); findings.append(r); scores.append(r["score"])
|
| 171 |
+
if "ela_image" in r: ela_img=r.pop("ela_image")
|
| 172 |
+
except Exception as e: findings.append({"test":fn.__name__,"error":str(e),"score":0})
|
| 173 |
+
avg=float(np.mean(scores)) if scores else 0.0; conf=min(1.0,0.5+0.5*abs(avg))
|
| 174 |
+
viol=[f["test"] for f in findings if f.get("score",0)>0.2]
|
| 175 |
+
comp=[f["test"] for f in findings if f.get("score",0)<-0.1]
|
| 176 |
+
rat=f"Metadata violations: {', '.join(viol)}." if viol else f"Metadata consistent: {', '.join(comp)}." if comp else "Metadata inconclusive."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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