Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,222 +2,138 @@ import gradio as gr
|
|
| 2 |
import numpy as np
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import cv2
|
|
|
|
| 5 |
from scipy import ndimage
|
| 6 |
|
| 7 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 8 |
-
# π¬
|
| 9 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 10 |
|
| 11 |
-
def
|
| 12 |
-
|
| 13 |
-
cr = ycrcb[:, :, 1].astype(np.float32)
|
| 14 |
-
cb = ycrcb[:, :, 2].astype(np.float32)
|
| 15 |
-
|
| 16 |
-
cr_var = ndimage.generic_filter(cr, np.var, size=5)
|
| 17 |
-
cb_var = ndimage.generic_filter(cb, np.var, size=5)
|
| 18 |
-
|
| 19 |
-
uniformity_cr = np.std(cr_var) / (np.mean(cr_var) + 1e-8)
|
| 20 |
-
uniformity_cb = np.std(cb_var) / (np.mean(cb_var) + 1e-8)
|
| 21 |
-
|
| 22 |
-
return (uniformity_cr + uniformity_cb) / 2, cr_var
|
| 23 |
-
|
| 24 |
-
def find_peaks(signal, threshold_factor=0.3):
|
| 25 |
-
if np.max(signal) == 0: return []
|
| 26 |
-
threshold = np.max(signal) * threshold_factor
|
| 27 |
-
peaks = []
|
| 28 |
-
for i in range(1, len(signal)-1):
|
| 29 |
-
if signal[i] > threshold and signal[i] > signal[i-1] and signal[i] > signal[i+1]:
|
| 30 |
-
peaks.append(i)
|
| 31 |
-
return peaks
|
| 32 |
-
|
| 33 |
-
def compute_radial_profile(image):
|
| 34 |
-
cy, cx = np.array(image.shape) // 2
|
| 35 |
-
y, x = np.indices(image.shape)
|
| 36 |
-
r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)
|
| 37 |
-
tbin = ndimage.mean(image, labels=r, index=np.arange(0, min(cx, cy)))
|
| 38 |
-
return tbin[~np.isnan(tbin)]
|
| 39 |
-
|
| 40 |
-
def detect_ringing(radial_profile):
|
| 41 |
-
if len(radial_profile) < 10: return 0
|
| 42 |
-
diff = np.diff(radial_profile)
|
| 43 |
-
# On ne compte que les changements de signe significatifs
|
| 44 |
-
sign_changes = np.sum((diff[1:] * diff[:-1] < 0) & (np.abs(diff[1:]) > 0.01))
|
| 45 |
-
return sign_changes / len(radial_profile)
|
| 46 |
-
|
| 47 |
-
def detect_grid_and_ringing(img):
|
| 48 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
|
| 49 |
-
f = np.fft.fft2(gray)
|
| 50 |
-
fshift = np.fft.fftshift(f)
|
| 51 |
-
magnitude = np.abs(fshift)
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
rows, cols = gray.shape
|
| 57 |
crow, ccol = rows//2, cols//2
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
mask = (x - ccol)**2 + (y - crow)**2 <= mask_radius**2
|
| 61 |
-
magnitude[mask] = 0
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
peaks_x =
|
| 66 |
-
peaks_y = len(find_peaks(proj_y, 0.4))
|
| 67 |
-
grid_score = (peaks_x + peaks_y) / 2
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
fft_vis = np.log(magnitude + 1)
|
| 73 |
-
fft_vis = (fft_vis - fft_vis.min()) / (fft_vis.max() - fft_vis.min() + 1e-8) * 255
|
| 74 |
-
fft_vis = cv2.applyColorMap(fft_vis.astype(np.uint8), cv2.COLORMAP_VIRIDIS)
|
| 75 |
-
|
| 76 |
-
return grid_score, ringing, fft_vis
|
| 77 |
-
|
| 78 |
-
def detect_noise_characteristics(img):
|
| 79 |
-
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
| 80 |
blur = cv2.GaussianBlur(gray, (5, 5), 0)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
noise_mean = np.mean(noise)
|
| 84 |
-
noise_std = np.std(noise)
|
| 85 |
-
|
| 86 |
-
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
|
| 87 |
-
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
|
| 88 |
-
grad_mag = np.sqrt(sobelx**2 + sobely**2)
|
| 89 |
-
hist = np.histogram(grad_mag, bins=50, range=(0, 255))[0]
|
| 90 |
-
grad_uniformity = np.std(hist) / (np.mean(hist) + 1e-8)
|
| 91 |
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
return {
|
| 95 |
-
'
|
| 96 |
-
'
|
| 97 |
-
'
|
| 98 |
-
'
|
|
|
|
| 99 |
}
|
| 100 |
|
| 101 |
-
def error_level_analysis(img, quality=90): # QualitΓ© montΓ©e Γ 90
|
| 102 |
-
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
|
| 103 |
-
_, enc = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR), encode_param)
|
| 104 |
-
dec = cv2.imdecode(enc, 1)
|
| 105 |
-
dec_rgb = cv2.cvtColor(dec, cv2.COLOR_BGR2RGB)
|
| 106 |
-
diff = cv2.absdiff(img, dec_rgb)
|
| 107 |
-
ela_score = np.mean(diff)
|
| 108 |
-
ela_enhanced = cv2.convertScaleAbs(diff, alpha=10.0)
|
| 109 |
-
return ela_score, ela_enhanced
|
| 110 |
-
|
| 111 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 112 |
-
# π§
|
| 113 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
|
| 115 |
def compute_ai_score(metrics):
|
| 116 |
score = 0
|
| 117 |
reasons = []
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
#
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
#
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
score += 25
|
| 136 |
-
reasons.append("
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
# 4. CHROMINANCE
|
| 149 |
-
if metrics['chrom_uniformity'] < 0.6:
|
| 150 |
-
score += 15
|
| 151 |
-
reasons.append("β‘ Artificial color distribution")
|
| 152 |
-
|
| 153 |
-
# LOGIQUE DE SΓCURITΓ FINALE
|
| 154 |
-
# Si on n'a qu'un seul indicateur faible, on bride le score Γ 30% (Probablement rΓ©el)
|
| 155 |
-
if confidence < 2 and score > 30:
|
| 156 |
-
score = 25 + (score * 0.1)
|
| 157 |
|
| 158 |
return min(score, 100), reasons
|
| 159 |
|
| 160 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 161 |
-
#
|
| 162 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 163 |
|
| 164 |
-
def
|
| 165 |
-
if
|
| 166 |
-
img = cv2.cvtColor(img_input, cv2.COLOR_RGBA2RGB) if img_input.shape[2] == 4 else img_input.copy()
|
| 167 |
|
| 168 |
-
|
|
|
|
| 169 |
if max(h, w) > 1024:
|
| 170 |
-
|
| 171 |
-
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
metrics = {
|
| 179 |
-
'chrom_uniformity': chrom_uniformity,
|
| 180 |
-
'grid_score': grid_score,
|
| 181 |
-
'ringing': ringing,
|
| 182 |
-
'noise_mean': noise_data['noise_mean'],
|
| 183 |
-
'noise_std': noise_data['noise_std'],
|
| 184 |
-
'grad_uniformity': noise_data['grad_uniformity'],
|
| 185 |
-
'laplacian': noise_data['laplacian'],
|
| 186 |
-
'ela_score': ela_score
|
| 187 |
-
}
|
| 188 |
|
| 189 |
-
|
|
|
|
| 190 |
|
| 191 |
-
#
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
# Visualisation
|
| 197 |
-
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
|
| 198 |
-
axes[0,0].imshow(img); axes[0,0].set_title('Original'); axes[0,0].axis('off')
|
| 199 |
-
axes[0,1].imshow(fft_vis); axes[0,1].set_title('FFT Analysis'); axes[0,1].axis('off')
|
| 200 |
-
axes[1,0].imshow(ela_vis); axes[1,0].set_title('ELA'); axes[1,0].axis('off')
|
| 201 |
-
axes[1,1].text(0.5, 0.5, f"Score: {ai_score:.1f}%\n{status}", ha='center', fontsize=14, fontweight='bold')
|
| 202 |
-
axes[1,1].axis('off')
|
| 203 |
-
plt.tight_layout()
|
| 204 |
-
|
| 205 |
-
report = f"VERDICT: {status}\nScore IA: {ai_score:.1f}/100\n\nIndicateurs :\n"
|
| 206 |
-
report += "\n".join([f" - {r}" for r in reasons]) if reasons else " - Aucun pattern suspect."
|
| 207 |
|
| 208 |
return fig, report
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
gr.Markdown("
|
| 213 |
with gr.Row():
|
| 214 |
with gr.Column():
|
| 215 |
-
|
| 216 |
-
btn = gr.Button("
|
| 217 |
with gr.Column():
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
btn.click(
|
| 221 |
|
| 222 |
if __name__ == "__main__":
|
| 223 |
demo.launch()
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import cv2
|
| 5 |
+
import os
|
| 6 |
from scipy import ndimage
|
| 7 |
|
| 8 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 9 |
+
# π¬ ANALYSE FORENSIQUE (COEUR DU SYSTΓME)
|
| 10 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
|
| 12 |
+
def get_metrics(img):
|
| 13 |
+
"""Extrait les signatures numΓ©riques de l'image"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
# 1. Analyse FrΓ©quentielle (FFT)
|
| 17 |
+
f = np.fft.fftshift(np.fft.fft2(gray))
|
| 18 |
+
mag = np.abs(f)
|
| 19 |
+
mag = mag / (np.mean(mag) + 1e-8)
|
| 20 |
+
|
| 21 |
+
# Masquage basse frΓ©quence
|
| 22 |
rows, cols = gray.shape
|
| 23 |
crow, ccol = rows//2, cols//2
|
| 24 |
+
mask = (np.ogrid[:rows, :cols][0] - crow)**2 + (np.ogrid[:rows, :cols][1] - ccol)**2 <= (min(rows, cols)//6)**2
|
| 25 |
+
mag[mask] = 0
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# Grid Score
|
| 28 |
+
proj_x = np.sum(mag, axis=0)
|
| 29 |
+
peaks_x = np.sum((proj_x > np.max(proj_x)*0.3) & (proj_x > np.roll(proj_x,1)) & (proj_x > np.roll(proj_x,-1)))
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# 2. Texture & Bruit
|
| 32 |
+
laplacian = cv2.Laplacian(gray, cv2.CV_64F).var()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
blur = cv2.GaussianBlur(gray, (5, 5), 0)
|
| 34 |
+
noise_mean = np.mean(cv2.absdiff(gray, blur))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
# 3. Chrominance
|
| 37 |
+
ycrcb = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
|
| 38 |
+
cr_var = ndimage.generic_filter(ycrcb[:,:,1].astype(np.float32), np.var, size=5)
|
| 39 |
+
chrom_uniformity = np.std(cr_var) / (np.mean(cr_var) + 1e-8)
|
| 40 |
|
| 41 |
+
# 4. ELA (Error Level Analysis)
|
| 42 |
+
_, enc = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90])
|
| 43 |
+
ela_score = np.mean(cv2.absdiff(img, cv2.cvtColor(cv2.imdecode(enc, 1), cv2.COLOR_BGR2RGB)))
|
| 44 |
+
|
| 45 |
return {
|
| 46 |
+
'grid_score': peaks_x,
|
| 47 |
+
'laplacian': laplacian,
|
| 48 |
+
'chrom_uniformity': chrom_uniformity,
|
| 49 |
+
'ela_score': ela_score,
|
| 50 |
+
'noise_mean': noise_mean
|
| 51 |
}
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
+
# π§ LOGIQUE DE SCORING COMBINΓE (HYBRIDE v2.6)
|
| 55 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
|
| 57 |
def compute_ai_score(metrics):
|
| 58 |
score = 0
|
| 59 |
reasons = []
|
| 60 |
+
confidence_hits = 0
|
| 61 |
+
|
| 62 |
+
# Filtres de RΓ©alitΓ© Organique
|
| 63 |
+
is_organic_noise = metrics['chrom_uniformity'] > 1.8
|
| 64 |
+
is_natural_texture = 150 < metrics['laplacian'] < 5000
|
| 65 |
+
|
| 66 |
+
# DΓTECTION DES STRUCTURES IA
|
| 67 |
+
# Grid Pattern : Très sensible pour démasquer les faux documents/armoires
|
| 68 |
+
if metrics['grid_score'] > 10:
|
| 69 |
+
score += 45
|
| 70 |
+
reasons.append("π¨ Signature structurelle IA dΓ©tectΓ©e (Grid Pattern)")
|
| 71 |
+
confidence_hits += 1
|
| 72 |
+
|
| 73 |
+
# ELA : Si l'image est "trop propre" numΓ©riquement
|
| 74 |
+
if metrics['ela_score'] < 1.4:
|
| 75 |
+
score += 30
|
| 76 |
+
reasons.append("β οΈ Compression suspecte (Image d'origine synthΓ©tique)")
|
| 77 |
+
confidence_hits += 1
|
| 78 |
+
|
| 79 |
+
# Chrominance : Lissage typique des modèles de diffusion
|
| 80 |
+
if metrics['chrom_uniformity'] < 0.8:
|
| 81 |
score += 25
|
| 82 |
+
reasons.append("β‘ Chrominance trop uniforme (Lissage IA)")
|
| 83 |
+
confidence_hits += 1
|
| 84 |
+
|
| 85 |
+
# LOGIQUE DE DΓCISION
|
| 86 |
+
# Si on a plusieurs indices de fake, on ignore le "pardon" organique
|
| 87 |
+
if confidence_hits >= 2:
|
| 88 |
+
score = max(score, 85)
|
| 89 |
+
|
| 90 |
+
# PROTECTION DES VRAIES PHOTOS (Comme ton portrait)
|
| 91 |
+
elif (is_organic_noise or is_natural_texture) and confidence_hits < 2:
|
| 92 |
+
score = min(score, 18)
|
| 93 |
+
reasons = ["β
Texture et bruit organiques confirmΓ©s"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
return min(score, 100), reasons
|
| 96 |
|
| 97 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 98 |
+
# π¨ INTERFACE ET ANALYSE
|
| 99 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 100 |
|
| 101 |
+
def run_shield(input_img):
|
| 102 |
+
if input_img is None: return None, "Aucune image"
|
|
|
|
| 103 |
|
| 104 |
+
# Resize pour performance
|
| 105 |
+
h, w = input_img.shape[:2]
|
| 106 |
if max(h, w) > 1024:
|
| 107 |
+
s = 1024 / max(h, w)
|
| 108 |
+
input_img = cv2.resize(input_img, (int(w*s), int(h*s)))
|
| 109 |
|
| 110 |
+
m = get_metrics(input_img)
|
| 111 |
+
score, reasons = compute_ai_score(m)
|
| 112 |
+
|
| 113 |
+
status = "β
AUTHENTIQUE" if score < 25 else "β οΈ SUSPECT" if score < 65 else "π¨ DEEPFAKE DΓTECTΓ"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
report = f"VERDICT : {status}\nScore de ProbabilitΓ© IA : {score:.1f}%\n\n"
|
| 116 |
+
report += "\n".join([f"- {r}" for r in reasons])
|
| 117 |
|
| 118 |
+
# Visualisation simple
|
| 119 |
+
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
|
| 120 |
+
ax.imshow(input_img)
|
| 121 |
+
ax.set_title(f"Score: {score:.1f}%")
|
| 122 |
+
ax.axis('off')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
return fig, report
|
| 125 |
|
| 126 |
+
with gr.Blocks(title="MAM SHIELD v2.6") as demo:
|
| 127 |
+
gr.Markdown("# π‘οΈ MAM SHIELD v2.6 β Forensic Image Analysis")
|
| 128 |
+
gr.Markdown("Système hybride combinant détection FFT et filtres de réalité organique.")
|
| 129 |
with gr.Row():
|
| 130 |
with gr.Column():
|
| 131 |
+
img_in = gr.Image(type="numpy")
|
| 132 |
+
btn = gr.Button("LANCER L'ANALYSE", variant="primary")
|
| 133 |
with gr.Column():
|
| 134 |
+
plot_out = gr.Plot()
|
| 135 |
+
txt_out = gr.Textbox(label="Rapport de Certification", lines=10)
|
| 136 |
+
btn.click(run_shield, inputs=img_in, outputs=[plot_out, txt_out])
|
| 137 |
|
| 138 |
if __name__ == "__main__":
|
| 139 |
demo.launch()
|