Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,404 +5,116 @@ import cv2
|
|
| 5 |
from scipy import ndimage
|
| 6 |
|
| 7 |
# ═══════════════════════════════════════════════════
|
| 8 |
-
# 🔬
|
| 9 |
# ═══════════════════════════════════════════════════
|
| 10 |
|
| 11 |
-
def
|
| 12 |
-
"""
|
| 13 |
-
Détecte l'uniformité anormale du bruit chromatique.
|
| 14 |
-
Les IA génèrent souvent du bruit trop régulier.
|
| 15 |
-
"""
|
| 16 |
-
ycrcb = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
|
| 17 |
-
cr = ycrcb[:, :, 1].astype(np.float32)
|
| 18 |
-
cb = ycrcb[:, :, 2].astype(np.float32)
|
| 19 |
-
|
| 20 |
-
# Variance locale sur des fenêtres 5x5
|
| 21 |
-
cr_var = ndimage.generic_filter(cr, np.var, size=5)
|
| 22 |
-
cb_var = ndimage.generic_filter(cb, np.var, size=5)
|
| 23 |
-
|
| 24 |
-
# Ratio: écart-type des variances / moyenne des variances
|
| 25 |
-
uniformity_cr = np.std(cr_var) / (np.mean(cr_var) + 1e-8)
|
| 26 |
-
uniformity_cb = np.std(cb_var) / (np.mean(cb_var) + 1e-8)
|
| 27 |
-
|
| 28 |
-
return (uniformity_cr + uniformity_cb) / 2, cr_var
|
| 29 |
-
|
| 30 |
-
def find_peaks(signal, threshold_factor=0.3):
|
| 31 |
-
"""Trouve les pics dans un signal 1D (pour détecter les grilles)"""
|
| 32 |
-
threshold = np.max(signal) * threshold_factor
|
| 33 |
-
peaks = []
|
| 34 |
-
for i in range(1, len(signal)-1):
|
| 35 |
-
if signal[i] > threshold and signal[i] > signal[i-1] and signal[i] > signal[i+1]:
|
| 36 |
-
peaks.append(i)
|
| 37 |
-
return peaks
|
| 38 |
-
|
| 39 |
-
def compute_radial_profile(image):
|
| 40 |
-
"""Calcule la moyenne radiale du spectre FFT"""
|
| 41 |
-
cy, cx = np.array(image.shape) // 2
|
| 42 |
-
y, x = np.indices(image.shape)
|
| 43 |
-
r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)
|
| 44 |
-
tbin = ndimage.mean(image, labels=r, index=np.arange(0, min(cx, cy)))
|
| 45 |
-
return tbin[~np.isnan(tbin)]
|
| 46 |
-
|
| 47 |
-
def detect_ringing(radial_profile):
|
| 48 |
-
"""
|
| 49 |
-
Détecte les oscillations (ringing) dans le profil radial.
|
| 50 |
-
Caractéristique des modèles de diffusion (SD, Midjourney).
|
| 51 |
-
"""
|
| 52 |
-
if len(radial_profile) < 10:
|
| 53 |
-
return 0
|
| 54 |
-
diff = np.diff(radial_profile)
|
| 55 |
-
sign_changes = np.sum(diff[1:] * diff[:-1] < 0)
|
| 56 |
-
return sign_changes / len(radial_profile)
|
| 57 |
-
|
| 58 |
-
def detect_grid_and_ringing(img):
|
| 59 |
-
"""
|
| 60 |
-
Détecte:
|
| 61 |
-
1. Les patterns de grille (StyleGAN, GANs)
|
| 62 |
-
2. Les artefacts circulaires (Diffusion models)
|
| 63 |
-
"""
|
| 64 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
|
| 71 |
-
#
|
|
|
|
|
|
|
| 72 |
rows, cols = gray.shape
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
magnitude[mask] = 0
|
| 78 |
-
|
| 79 |
-
# Détection de grille via projection
|
| 80 |
-
proj_x = np.sum(magnitude, axis=0)
|
| 81 |
-
proj_y = np.sum(magnitude, axis=1)
|
| 82 |
-
peaks_x = len(find_peaks(proj_x, 0.2))
|
| 83 |
-
peaks_y = len(find_peaks(proj_y, 0.2))
|
| 84 |
-
grid_score = (peaks_x + peaks_y) / 2
|
| 85 |
-
|
| 86 |
-
# Détection du ringing
|
| 87 |
-
radial = compute_radial_profile(magnitude)
|
| 88 |
-
ringing = detect_ringing(radial)
|
| 89 |
-
|
| 90 |
-
# Visualisation
|
| 91 |
-
fft_vis = np.log(magnitude + 1)
|
| 92 |
-
fft_vis = (fft_vis - fft_vis.min()) / (fft_vis.max() - fft_vis.min()) * 255
|
| 93 |
-
fft_vis = cv2.applyColorMap(fft_vis.astype(np.uint8), cv2.COLORMAP_VIRIDIS)
|
| 94 |
-
|
| 95 |
-
return grid_score, ringing, fft_vis
|
| 96 |
-
|
| 97 |
-
def detect_noise_characteristics(img):
|
| 98 |
-
"""
|
| 99 |
-
Analyse le bruit local (les images IA ont des statistiques de bruit anormales)
|
| 100 |
-
"""
|
| 101 |
-
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
| 102 |
-
|
| 103 |
-
# Différence entre image et version lissée
|
| 104 |
-
blur = cv2.GaussianBlur(gray, (5, 5), 0)
|
| 105 |
-
noise = cv2.absdiff(gray, blur)
|
| 106 |
-
|
| 107 |
-
# Statistiques
|
| 108 |
-
noise_mean = np.mean(noise)
|
| 109 |
-
noise_std = np.std(noise)
|
| 110 |
-
|
| 111 |
-
# Analyse des gradients (Sobel)
|
| 112 |
-
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
|
| 113 |
-
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
|
| 114 |
-
grad_mag = np.sqrt(sobelx**2 + sobely**2)
|
| 115 |
-
|
| 116 |
-
# Distribution des gradients
|
| 117 |
-
hist = np.histogram(grad_mag, bins=50, range=(0, 255))[0]
|
| 118 |
-
grad_uniformity = np.std(hist) / (np.mean(hist) + 1e-8)
|
| 119 |
|
| 120 |
-
#
|
| 121 |
laplacian = cv2.Laplacian(gray, cv2.CV_64F).var()
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
return {
|
| 124 |
-
'
|
| 125 |
-
'
|
| 126 |
-
'
|
| 127 |
-
'
|
|
|
|
| 128 |
}
|
| 129 |
|
| 130 |
-
def error_level_analysis(img, quality=85):
|
| 131 |
-
"""
|
| 132 |
-
ELA: Recompresser l'image et comparer.
|
| 133 |
-
Les zones générées par IA ont souvent des niveaux d'erreur anormaux.
|
| 134 |
-
"""
|
| 135 |
-
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
|
| 136 |
-
_, enc = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR), encode_param)
|
| 137 |
-
dec = cv2.imdecode(enc, 1)
|
| 138 |
-
dec_rgb = cv2.cvtColor(dec, cv2.COLOR_BGR2RGB)
|
| 139 |
-
|
| 140 |
-
diff = cv2.absdiff(img, dec_rgb)
|
| 141 |
-
ela_score = np.mean(diff)
|
| 142 |
-
|
| 143 |
-
# Améliorer la visualisation
|
| 144 |
-
ela_enhanced = cv2.convertScaleAbs(diff, alpha=5.0)
|
| 145 |
-
|
| 146 |
-
return ela_score, ela_enhanced
|
| 147 |
-
|
| 148 |
# ═══════════════════════════════════════════════════
|
| 149 |
-
# 🧠 ALGORITHME DE
|
| 150 |
# ═══════════════════════════════════════════════════
|
| 151 |
|
| 152 |
-
def compute_ai_score(
|
| 153 |
-
"""
|
| 154 |
-
Système de scoring pondéré avec logique floue.
|
| 155 |
-
Seuils calibrés pour minimiser les faux positifs.
|
| 156 |
-
"""
|
| 157 |
score = 0
|
| 158 |
reasons = []
|
| 159 |
confidence = 0
|
| 160 |
-
|
| 161 |
-
#
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
if metrics['ringing'] > 0.25:
|
| 172 |
-
score += 25
|
| 173 |
-
reasons.append("⚠️ Circular artifacts (Stable Diffusion/Midjourney)")
|
| 174 |
-
confidence += 1
|
| 175 |
-
elif metrics['ringing'] > 0.15:
|
| 176 |
-
score += 12
|
| 177 |
-
reasons.append("⚡ Possible diffusion artifacts")
|
| 178 |
-
|
| 179 |
-
# 3. CHROMINANCE (Natural vs AI noise)
|
| 180 |
-
if metrics['chrom_uniformity'] < 1.0: # Trop uniforme = suspect
|
| 181 |
-
score += 15
|
| 182 |
-
reasons.append("⚡ Unnatural chrominance uniformity")
|
| 183 |
-
elif metrics['chrom_uniformity'] < 0.5:
|
| 184 |
-
score += 25
|
| 185 |
-
reasons.append("⚠️ Artificial color noise detected")
|
| 186 |
confidence += 1
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
reasons.append("⚡ Suspiciously low noise (over-smoothed)")
|
| 192 |
-
elif metrics['noise_mean'] > 40: # Bruit artificiel
|
| 193 |
-
score += 10
|
| 194 |
-
reasons.append("⚡ Artificial noise pattern")
|
| 195 |
-
|
| 196 |
-
# 5. GRADIENT DISTRIBUTION
|
| 197 |
-
if metrics['grad_uniformity'] < 2.0:
|
| 198 |
-
score += 10
|
| 199 |
-
reasons.append("⚡ Unnatural edge distribution")
|
| 200 |
-
|
| 201 |
-
# 6. LAPLACIAN (Texture)
|
| 202 |
-
if metrics['laplacian'] < 50:
|
| 203 |
-
score += 10
|
| 204 |
-
reasons.append("⚡ Lack of fine texture details")
|
| 205 |
-
elif metrics['laplacian'] > 500000: # Images très détaillées (possible upscaling IA)
|
| 206 |
-
score += 10
|
| 207 |
-
reasons.append("⚡ Excessive sharpness (AI upscaling?)")
|
| 208 |
-
|
| 209 |
-
# 7. ELA
|
| 210 |
-
if metrics['ela_score'] < 1.5:
|
| 211 |
-
score += 15
|
| 212 |
-
reasons.append("⚠️ Suspicious compression history")
|
| 213 |
confidence += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
return min(score, 100), reasons
|
| 220 |
|
| 221 |
# ═══════════════════════════════════════════════════
|
| 222 |
-
# 🎯 FONCTION PRINCIPALE
|
| 223 |
# ═══════════════════════════════════════════════════
|
| 224 |
|
| 225 |
-
def
|
| 226 |
-
if
|
| 227 |
-
return None, "Erreur : aucune image fournie"
|
| 228 |
-
|
| 229 |
-
# Conversion RGBA → RGB si nécessaire
|
| 230 |
-
if img_input.shape[2] == 4:
|
| 231 |
-
img = cv2.cvtColor(img_input, cv2.COLOR_RGBA2RGB)
|
| 232 |
-
else:
|
| 233 |
-
img = img_input.copy()
|
| 234 |
-
|
| 235 |
-
# Limiter la taille pour accélérer (mais garder la qualité)
|
| 236 |
-
h, w = img.shape[:2]
|
| 237 |
-
if max(h, w) > 1024:
|
| 238 |
-
scale = 1024 / max(h, w)
|
| 239 |
-
img = cv2.resize(img, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_AREA)
|
| 240 |
-
|
| 241 |
-
# Exécuter les analyses
|
| 242 |
-
chrom_uniformity, chrom_vis = analyze_chrominance_noise(img)
|
| 243 |
-
grid_score, ringing, fft_vis = detect_grid_and_ringing(img)
|
| 244 |
-
noise_data = detect_noise_characteristics(img)
|
| 245 |
-
ela_score, ela_vis = error_level_analysis(img)
|
| 246 |
-
|
| 247 |
-
metrics = {
|
| 248 |
-
'chrom_uniformity': chrom_uniformity,
|
| 249 |
-
'grid_score': grid_score,
|
| 250 |
-
'ringing': ringing,
|
| 251 |
-
'noise_mean': noise_data['noise_mean'],
|
| 252 |
-
'noise_std': noise_data['noise_std'],
|
| 253 |
-
'grad_uniformity': noise_data['grad_uniformity'],
|
| 254 |
-
'laplacian': noise_data['laplacian'],
|
| 255 |
-
'ela_score': ela_score
|
| 256 |
-
}
|
| 257 |
-
|
| 258 |
-
# Calcul du score
|
| 259 |
-
ai_score, reasons = compute_ai_score(metrics)
|
| 260 |
-
|
| 261 |
-
# Classification avec nuance
|
| 262 |
-
if ai_score >= 80:
|
| 263 |
-
status = "🚨 AI GENERATED (High Confidence)"
|
| 264 |
-
color = "#ff4444"
|
| 265 |
-
elif ai_score >= 60:
|
| 266 |
-
status = "⚠️ LIKELY AI / HEAVILY EDITED"
|
| 267 |
-
color = "#ff8844"
|
| 268 |
-
elif ai_score >= 40:
|
| 269 |
-
status = "🔍 SUSPICIOUS – Manual Review Recommended"
|
| 270 |
-
color = "#ffaa44"
|
| 271 |
-
elif ai_score >= 20:
|
| 272 |
-
status = "✓ PROBABLY REAL (Low Confidence)"
|
| 273 |
-
color = "#88cc44"
|
| 274 |
-
else:
|
| 275 |
-
status = "✅ AUTHENTIC IMAGE"
|
| 276 |
-
color = "#44aa44"
|
| 277 |
-
|
| 278 |
-
# Détection du type
|
| 279 |
-
if grid_score > 10 and ringing > 0.2:
|
| 280 |
-
model_type = "StyleGAN or ProGAN (grid + ringing)"
|
| 281 |
-
elif ringing > 0.25:
|
| 282 |
-
model_type = "Stable Diffusion / Midjourney / DALL-E"
|
| 283 |
-
elif grid_score > 10:
|
| 284 |
-
model_type = "GAN-based (StyleGAN legacy)"
|
| 285 |
-
elif ai_score > 50:
|
| 286 |
-
model_type = "Unknown AI / Heavy processing"
|
| 287 |
-
else:
|
| 288 |
-
model_type = "Natural/Camera capture"
|
| 289 |
-
|
| 290 |
-
# Visualisations
|
| 291 |
-
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 292 |
-
fig.patch.set_facecolor('#f0f0f0')
|
| 293 |
-
|
| 294 |
-
# Original
|
| 295 |
-
axes[0,0].imshow(img)
|
| 296 |
-
axes[0,0].set_title('📸 Original Image', fontsize=12, fontweight='bold')
|
| 297 |
-
axes[0,0].axis('off')
|
| 298 |
-
|
| 299 |
-
# FFT
|
| 300 |
-
axes[0,1].imshow(fft_vis)
|
| 301 |
-
axes[0,1].set_title(f'🔮 Frequency Analysis\nGrid: {grid_score:.1f} | Ringing: {ringing:.2f}',
|
| 302 |
-
fontsize=11, fontweight='bold')
|
| 303 |
-
axes[0,1].axis('off')
|
| 304 |
-
|
| 305 |
-
# ELA
|
| 306 |
-
axes[1,0].imshow(ela_vis)
|
| 307 |
-
axes[1,0].set_title(f'🔍 Error Level Analysis\nScore: {ela_score:.2f}',
|
| 308 |
-
fontsize=11, fontweight='bold')
|
| 309 |
-
axes[1,0].axis('off')
|
| 310 |
-
|
| 311 |
-
# Chrominance
|
| 312 |
-
im = axes[1,1].imshow(chrom_vis, cmap='hot')
|
| 313 |
-
axes[1,1].set_title(f'🌈 Chrominance Noise\nUniformity: {chrom_uniformity:.2f}',
|
| 314 |
-
fontsize=11, fontweight='bold')
|
| 315 |
-
axes[1,1].axis('off')
|
| 316 |
-
plt.colorbar(im, ax=axes[1,1], fraction=0.046)
|
| 317 |
-
|
| 318 |
-
plt.tight_layout()
|
| 319 |
-
|
| 320 |
-
# Rapport détaillé
|
| 321 |
-
report = f"""
|
| 322 |
-
╔══════════════════════════════════════════════════════════╗
|
| 323 |
-
║ 🛡️ MEDIASHIELD PRO – FORENSIC ANALYSIS v2.0 ║
|
| 324 |
-
╚══════════════════════════════════════════════════════════╝
|
| 325 |
-
|
| 326 |
-
📊 FINAL VERDICT: {status}
|
| 327 |
-
🎯 AI PROBABILITY SCORE: {ai_score}/100
|
| 328 |
-
|
| 329 |
-
🔬 DETAILED METRICS:
|
| 330 |
-
├─ Grid Pattern Score: {grid_score:>6.2f} {'⚠️' if grid_score > 8 else '✓'}
|
| 331 |
-
├─ Circular Artifacts: {ringing:>6.3f} {'⚠️' if ringing > 0.15 else '✓'}
|
| 332 |
-
├─ Chrominance Uniformity: {chrom_uniformity:>6.2f} {'⚠️' if chrom_uniformity < 1.0 else '✓'}
|
| 333 |
-
├─ Noise Level: {noise_data['noise_mean']:>6.2f} ±{noise_data['noise_std']:.2f}
|
| 334 |
-
├─ Gradient Uniformity: {noise_data['grad_uniformity']:>6.2f}
|
| 335 |
-
├─ Texture (Laplacian): {noise_data['laplacian']:>6.0f}
|
| 336 |
-
└─ ELA Score: {ela_score:>6.2f} {'⚠️' if ela_score < 1.5 else '✓'}
|
| 337 |
-
|
| 338 |
-
📝 DETECTED INDICATORS:"""
|
| 339 |
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
else:
|
| 344 |
-
report += "\n ✅ No suspicious patterns detected"
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
🤖 ESTIMATED SOURCE: {model_type}
|
| 349 |
-
|
| 350 |
-
💡 INTERPRETATION:
|
| 351 |
-
"""
|
| 352 |
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
elif ai_score >= 60:
|
| 356 |
-
report += "This image likely contains AI-generated elements or heavy manipulation."
|
| 357 |
-
elif ai_score >= 40:
|
| 358 |
-
report += "Some anomalies detected. Recommend expert verification."
|
| 359 |
-
else:
|
| 360 |
-
report += "Image characteristics consistent with natural photography."
|
| 361 |
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
═══════════════════════════════════════════════════════════"""
|
| 367 |
|
| 368 |
return fig, report
|
| 369 |
|
| 370 |
-
|
| 371 |
-
#
|
| 372 |
-
# ═══════════════════════════════════════════════════
|
| 373 |
-
|
| 374 |
-
css = """
|
| 375 |
-
.output_text { font-family: 'Courier New', monospace; white-space: pre-line; }
|
| 376 |
-
"""
|
| 377 |
-
|
| 378 |
-
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
| 379 |
-
gr.Markdown("""
|
| 380 |
-
# 🛡️ MediaShield PRO – AI Image Detection v2.0
|
| 381 |
-
### Détection avancée de Deepfakes, Stable Diffusion, Midjourney et GANs
|
| 382 |
-
""")
|
| 383 |
-
|
| 384 |
with gr.Row():
|
| 385 |
-
with gr.Column(
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
gr.
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
- ⚠️ **60-79**: Probablement IA ou très retouchée
|
| 393 |
-
- 🔍 **40-59**: Suspecte – vérification manuelle recommandée
|
| 394 |
-
- ✅ **0-39**: Image probablement authentique
|
| 395 |
-
""")
|
| 396 |
-
|
| 397 |
-
with gr.Column(scale=2):
|
| 398 |
-
output_plot = gr.Plot(label="🔬 Forensic Visualizations")
|
| 399 |
-
output_text = gr.Textbox(label="📋 Analysis Report", lines=25, elem_classes=["output_text"])
|
| 400 |
-
|
| 401 |
-
analyze_btn.click(
|
| 402 |
-
fn=analyze_image,
|
| 403 |
-
inputs=input_img,
|
| 404 |
-
outputs=[output_plot, output_text]
|
| 405 |
-
)
|
| 406 |
|
| 407 |
if __name__ == "__main__":
|
| 408 |
demo.launch()
|
|
|
|
| 5 |
from scipy import ndimage
|
| 6 |
|
| 7 |
# ═══════════════════════════════════════════════════
|
| 8 |
+
# 🔬 ANALYSE DES SIGNATURES NUMÉRIQUES
|
| 9 |
# ═══════════════════════════════════════════════════
|
| 10 |
|
| 11 |
+
def get_advanced_metrics(img):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
|
| 13 |
|
| 14 |
+
# 1. Analyse du Grain (Chrominance)
|
| 15 |
+
ycrcb = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
|
| 16 |
+
cr_var = ndimage.generic_filter(ycrcb[:,:,1].astype(np.float32), np.var, size=5)
|
| 17 |
+
chrom_uniformity = np.std(cr_var) / (np.mean(cr_var) + 1e-8)
|
| 18 |
|
| 19 |
+
# 2. Analyse Fréquentielle (FFT)
|
| 20 |
+
fshift = np.fft.fftshift(np.fft.fft2(gray))
|
| 21 |
+
mag = np.abs(fshift)
|
| 22 |
rows, cols = gray.shape
|
| 23 |
+
mask = (np.ogrid[:rows, :cols][0] - rows//2)**2 + (np.ogrid[:rows, :cols][1] - cols//2)**2 <= (min(rows, cols)//6)**2
|
| 24 |
+
mag[mask] = 0
|
| 25 |
+
proj_x = np.sum(mag, axis=0)
|
| 26 |
+
grid_score = np.sum((proj_x > np.max(proj_x)*0.3) & (proj_x > np.roll(proj_x,1)) & (proj_x > np.roll(proj_x,-1)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
# 3. Texture (Laplacian)
|
| 29 |
laplacian = cv2.Laplacian(gray, cv2.CV_64F).var()
|
| 30 |
|
| 31 |
+
# 4. ELA (Erreur de compression)
|
| 32 |
+
_, enc = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90])
|
| 33 |
+
ela_score = np.mean(cv2.absdiff(img, cv2.cvtColor(cv2.imdecode(enc, 1), cv2.COLOR_BGR2RGB)))
|
| 34 |
+
|
| 35 |
return {
|
| 36 |
+
'chrom_uniformity': chrom_uniformity,
|
| 37 |
+
'grid_score': grid_score,
|
| 38 |
+
'laplacian': laplacian,
|
| 39 |
+
'ela_score': ela_score,
|
| 40 |
+
'brightness': np.mean(gray)
|
| 41 |
}
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# ═══════════════════════════════════════════════════
|
| 44 |
+
# 🧠 ALGORITHME DE DÉCISION (LOGIQUE DE PARDON)
|
| 45 |
# ═══════════════════════════════════════════════════
|
| 46 |
|
| 47 |
+
def compute_ai_score(m):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
score = 0
|
| 49 |
reasons = []
|
| 50 |
confidence = 0
|
| 51 |
+
|
| 52 |
+
# --- ÉTAPE 1 : IDENTIFICATION DU BRUIT RÉEL ---
|
| 53 |
+
# Si le bruit est "sale" et irrégulier (chrom_uniformity > 1.8), c'est une photo.
|
| 54 |
+
is_organic = m['chrom_uniformity'] > 1.6
|
| 55 |
+
# Si la texture est complexe et variée
|
| 56 |
+
is_natural_texture = 200 < m['laplacian'] < 8000
|
| 57 |
+
|
| 58 |
+
# --- ÉTAPE 2 : DÉTECTION IA ---
|
| 59 |
+
if m['grid_score'] > 25:
|
| 60 |
+
score += 40
|
| 61 |
+
reasons.append("⚠️ Grid patterns (IA signature)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
confidence += 1
|
| 63 |
+
|
| 64 |
+
if m['ela_score'] < 1.2:
|
| 65 |
+
score += 30
|
| 66 |
+
reasons.append("⚠️ High digital purity (AI characteristic)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
confidence += 1
|
| 68 |
+
|
| 69 |
+
# --- ÉTAPE 3 : LE FILTRE DE RÉALITÉ (Correction des erreurs) ---
|
| 70 |
+
if is_organic:
|
| 71 |
+
score *= 0.5 # On réduit le score de moitié car le grain semble vrai
|
| 72 |
+
reasons.append("✅ Organic noise detected (Sensor grain)")
|
| 73 |
|
| 74 |
+
if is_natural_texture and confidence < 2:
|
| 75 |
+
score = min(score, 15) # On force le passage en vert si la texture est naturelle
|
| 76 |
+
reasons = ["✅ Natural texture patterns confirmed"]
|
| 77 |
+
|
| 78 |
+
# Gestion des images sombres
|
| 79 |
+
if m['brightness'] < 40:
|
| 80 |
+
score *= 0.8
|
| 81 |
+
reasons.append("ℹ️ Low-light compensation applied")
|
| 82 |
+
|
| 83 |
return min(score, 100), reasons
|
| 84 |
|
| 85 |
# ═══════════════════════════════════════════════════
|
| 86 |
+
# 🎯 FONCTION PRINCIPALE
|
| 87 |
# ═══════════════════════════════════════════════════
|
| 88 |
|
| 89 |
+
def run_shield(image):
|
| 90 |
+
if image is None: return None, "No image"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
img = image.copy()
|
| 93 |
+
m = get_advanced_metrics(img)
|
| 94 |
+
score, reasons = compute_ai_score(m)
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
status = "✅ AUTHENTIQUE" if score < 25 else "⚠️ SUSPECT" if score < 65 else "🚨 DEEPFAKE"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
report = f"VERDICT : {status}\nProbabilité IA : {score:.1f}%\n\n"
|
| 99 |
+
report += "\n".join([f"- {r}" for r in reasons])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
fig, ax = plt.subplots()
|
| 102 |
+
ax.imshow(img)
|
| 103 |
+
ax.set_title(f"MAM SHIELD - Score: {score:.1f}%")
|
| 104 |
+
ax.axis('off')
|
|
|
|
| 105 |
|
| 106 |
return fig, report
|
| 107 |
|
| 108 |
+
with gr.Blocks(title="MediaShield v2.2") as demo:
|
| 109 |
+
gr.Markdown("# 🛡️ MediaShield PRO v2.2 (Correctif Anti-Faux Positifs)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
with gr.Row():
|
| 111 |
+
with gr.Column():
|
| 112 |
+
in_img = gr.Image(type="numpy")
|
| 113 |
+
btn = gr.Button("VÉRIFIER", variant="primary")
|
| 114 |
+
with gr.Column():
|
| 115 |
+
out_plot = gr.Plot()
|
| 116 |
+
out_txt = gr.Textbox(label="Rapport", lines=10)
|
| 117 |
+
btn.click(run_shield, in_img, [out_plot, out_txt])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
| 120 |
demo.launch()
|