anky2002 commited on
Commit
27f7870
Β·
verified Β·
1 Parent(s): ada1738

Upload agents/metadata_agent.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. agents/metadata_agent.py +290 -0
agents/metadata_agent.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FORENSIQ β€” Metadata Agent
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, GPSTAGS
12
+ import io
13
+ import struct
14
+ from typing import Dict, Any, List, Tuple
15
+
16
+ from agents.optical_agent import AgentEvidence
17
+
18
+
19
+ # ─── EXIF Validation ─────────────────────────────────────────────────
20
+ def analyze_exif(img: Image.Image) -> Dict[str, Any]:
21
+ """
22
+ Check EXIF metadata completeness and physical plausibility.
23
+ Real photos have rich EXIF; AI images have none or fabricated metadata.
24
+ """
25
+ try:
26
+ exif_data = img._getexif() or {}
27
+ except Exception:
28
+ exif_data = {}
29
+
30
+ decoded = {}
31
+ for tag_id, value in exif_data.items():
32
+ tag = TAGS.get(tag_id, str(tag_id))
33
+ try:
34
+ decoded[tag] = str(value)[:200]
35
+ except Exception:
36
+ decoded[tag] = "<binary>"
37
+
38
+ suspicious_flags = []
39
+ authenticity_markers = []
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
+ # ─── Main Agent Entry Point ─────────────────────────────────────────
245
+ def run_metadata_agent(img: Image.Image) -> AgentEvidence:
246
+ """Run all metadata analysis tests."""
247
+ findings = []
248
+ scores = []
249
+
250
+ for fn in [analyze_exif, analyze_ela, analyze_ai_metadata]:
251
+ try:
252
+ result = fn(img)
253
+ findings.append(result)
254
+ scores.append(result["score"])
255
+ except Exception as e:
256
+ findings.append({"test": fn.__name__, "error": str(e), "score": 0})
257
+
258
+ avg_score = float(np.mean(scores)) if scores else 0.0
259
+ confidence = min(1.0, 0.5 + 0.5 * abs(avg_score))
260
+
261
+ violations = [f["test"] for f in findings if f.get("score", 0) > 0.2]
262
+ compliant = [f["test"] for f in findings if f.get("score", 0) < -0.1]
263
+
264
+ if violations:
265
+ rationale = f"Metadata violations: {', '.join(violations)}."
266
+ elif compliant:
267
+ rationale = f"Metadata consistent: {', '.join(compliant)}."
268
+ else:
269
+ rationale = "Metadata analysis inconclusive."
270
+
271
+ for f in findings:
272
+ if f.get("note"):
273
+ rationale += f" [{f['test']}]: {f['note']}."
274
+
275
+ # Extract ELA image if available
276
+ ela_img = None
277
+ for f in findings:
278
+ if "ela_image" in f:
279
+ ela_img = f["ela_image"]
280
+ del f["ela_image"] # Don't include in serializable findings
281
+
282
+ return AgentEvidence(
283
+ agent_name="Metadata Agent",
284
+ violation_score=np.clip(avg_score, -1, 1),
285
+ confidence=confidence,
286
+ failure_prob=max(0.0, 1.0 - len(scores) / 3),
287
+ rationale=rationale,
288
+ sub_findings=findings,
289
+ visual_evidence=ela_img,
290
+ )