NOBODY204 commited on
Commit
aa960c7
Β·
verified Β·
1 Parent(s): 24594b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -175
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
- # πŸ”¬ MEDIASHIELD PRO v2.1 – CORRECTIF PHOTO RΓ‰ELLE
9
  # ═══════════════════════════════════════════════════
10
 
11
- def analyze_chrominance_noise(img):
12
- ycrcb = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
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
- # Normalisation pour Γ©viter l'explosion des scores sur photos sombres
54
- magnitude = magnitude / (np.mean(magnitude) + 1e-8)
55
-
 
 
 
56
  rows, cols = gray.shape
57
  crow, ccol = rows//2, cols//2
58
- mask_radius = min(rows, cols) // 6
59
- y, x = np.ogrid[:rows, :cols]
60
- mask = (x - ccol)**2 + (y - crow)**2 <= mask_radius**2
61
- magnitude[mask] = 0
62
 
63
- proj_x = np.sum(magnitude, axis=0)
64
- proj_y = np.sum(magnitude, axis=1)
65
- peaks_x = len(find_peaks(proj_x, 0.4)) # Seuil montΓ© Γ  0.4
66
- peaks_y = len(find_peaks(proj_y, 0.4))
67
- grid_score = (peaks_x + peaks_y) / 2
68
 
69
- radial = compute_radial_profile(magnitude)
70
- ringing = detect_ringing(radial)
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
- noise = cv2.absdiff(gray, blur)
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
- laplacian = cv2.Laplacian(gray, cv2.CV_64F).var()
 
 
 
93
 
 
 
 
 
94
  return {
95
- 'noise_mean': noise_mean,
96
- 'noise_std': noise_std,
97
- 'grad_uniformity': grad_uniformity,
98
- 'laplacian': laplacian
 
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
- # 🧠 ALGORITHME DE SCORING SΓ‰CURISΓ‰
113
  # ═══════════════════════════════════════════════════
114
 
115
  def compute_ai_score(metrics):
116
  score = 0
117
  reasons = []
118
- confidence = 0
119
-
120
- # PROTECTION : DΓ©tection des photos lisses ou sombres
121
- is_smooth = metrics['laplacian'] < 150
122
- is_compressed = metrics['ela_score'] < 1.0
123
-
124
- # 1. GRID PATTERNS (Seuils beaucoup plus hauts)
125
- if metrics['grid_score'] > 40:
126
- score += 35
127
- reasons.append("⚠️ Strong grid patterns (GAN signature)")
128
- confidence += 1
129
- elif metrics['grid_score'] > 20 and not is_smooth:
130
- score += 15
131
- reasons.append("⚑ Unnatural frequency spikes")
132
-
133
- # 2. RINGING (Seuils ajustΓ©s pour le bruit rΓ©el)
134
- if metrics['ringing'] > 0.45:
 
 
 
 
135
  score += 25
136
- reasons.append("⚠️ Circular diffusion artifacts detected")
137
- confidence += 1
138
- elif metrics['ringing'] > 0.30 and not is_compressed:
139
- score += 12
140
- reasons.append("⚑ Slight ringing oscillations")
141
-
142
- # 3. ELA (On ne pénalise que si c'est EXTRÊMEMENT bas)
143
- if metrics['ela_score'] < 0.4:
144
- score += 20
145
- reasons.append("⚠️ Zero-noise compression (Highly suspicious)")
146
- confidence += 1
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
- # 🎯 FONCTION PRINCIPALE
162
  # ═══════════════════════════════════════════════════
163
 
164
- def analyze_image(img_input):
165
- if img_input is None: return None, "Erreur"
166
- img = cv2.cvtColor(img_input, cv2.COLOR_RGBA2RGB) if img_input.shape[2] == 4 else img_input.copy()
167
 
168
- h, w = img.shape[:2]
 
169
  if max(h, w) > 1024:
170
- scale = 1024 / max(h, w)
171
- img = cv2.resize(img, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_AREA)
172
 
173
- chrom_uniformity, _ = analyze_chrominance_noise(img)
174
- grid_score, ringing, fft_vis = detect_grid_and_ringing(img)
175
- noise_data = detect_noise_characteristics(img)
176
- ela_score, ela_vis = error_level_analysis(img)
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
- ai_score, reasons = compute_ai_score(metrics)
 
190
 
191
- # Classification
192
- if ai_score >= 75: status = "🚨 AI GENERATED"
193
- elif ai_score >= 50: status = "⚠️ SUSPICIOUS / EDITED"
194
- else: status = "βœ… AUTHENTIC IMAGE"
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
- # 🎨 GRADIO
211
- with gr.Blocks() as demo:
212
- gr.Markdown("# πŸ›‘οΈ MediaShield PRO v2.1")
213
  with gr.Row():
214
  with gr.Column():
215
- in_img = gr.Image(type="numpy")
216
- btn = gr.Button("ANALYSER", variant="primary")
217
  with gr.Column():
218
- out_plot = gr.Plot()
219
- out_txt = gr.Textbox(label="Rapport")
220
- btn.click(analyze_image, inputs=in_img, outputs=[out_plot, out_txt])
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()