NOBODY204 commited on
Commit
dc172c8
ยท
verified ยท
1 Parent(s): 8ca0a0d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -61
app.py CHANGED
@@ -5,28 +5,45 @@ import cv2
5
  from scipy import ndimage
6
 
7
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
8
- # ๐Ÿ›ก๏ธ MEDIASHIELD PRO v2.2 โ€“ ร‰DITION SOUVERAINE 2026
9
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
10
 
11
- def analyze_sensor_noise(img):
12
- """Analyse du grain (PRNU simplifiรฉ). Les IA ont un bruit trop 'mathรฉmatique'."""
13
- gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
14
- noise_extract = gray - cv2.medianBlur(gray, 3)
15
- return np.var(noise_extract), noise_extract
 
 
 
 
 
 
 
 
16
 
17
- def find_peaks_smart(signal, threshold_factor=0.25, is_fft=False):
18
- """Dรฉtecteur de pics qui ignore les multiples de 8 (signatures du JPEG)."""
19
  threshold = np.max(signal) * threshold_factor
20
  peaks = []
21
  for i in range(1, len(signal)-1):
22
- # FILTRE ANTI-JPEG : On ignore les frรฉquences de compression standard
23
- if is_fft and (i % 8 == 0): continue
24
  if signal[i] > threshold and signal[i] > signal[i-1] and signal[i] > signal[i+1]:
25
  peaks.append(i)
26
  return peaks
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def detect_grid_and_ringing(img):
29
- """Analyse frรฉquentielle (FFT) pour dรฉtecter GANs et modรจles de Diffusion."""
30
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
31
  f = np.fft.fft2(gray)
32
  fshift = np.fft.fftshift(f)
@@ -34,88 +51,122 @@ def detect_grid_and_ringing(img):
34
 
35
  rows, cols = gray.shape
36
  crow, ccol = rows//2, cols//2
37
-
38
- # Masque central pour ignorer le contenu global de l'image
39
- mask_radius = min(rows, cols) // 10
40
  y, x = np.ogrid[:rows, :cols]
41
- magnitude[(x - ccol)**2 + (y - crow)**2 <= mask_radius**2] = 0
 
42
 
43
- # Projection et dรฉtection des pics (avec filtre anti-JPEG)
44
  proj_x = np.sum(magnitude, axis=0)
45
  proj_y = np.sum(magnitude, axis=1)
46
- grid_score = (len(find_peaks_smart(proj_x, 0.25, True)) + len(find_peaks_smart(proj_y, 0.25, True))) / 2
 
 
 
47
 
48
  fft_vis = np.log(magnitude + 1)
49
  fft_vis = (fft_vis - fft_vis.min()) / (fft_vis.max() - fft_vis.min() + 1e-8) * 255
50
- return grid_score, cv2.applyColorMap(fft_vis.astype(np.uint8), cv2.COLORMAP_VIRIDIS)
 
 
51
 
52
- def error_level_analysis(img, quality=90):
53
- """ELA : Dรฉtecte les diffรฉrences de compression locales."""
54
  encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
55
  _, enc = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR), encode_param)
56
  dec = cv2.imdecode(enc, 1)
57
- diff = cv2.absdiff(img, cv2.cvtColor(dec, cv2.COLOR_BGR2RGB))
58
- return np.mean(diff), cv2.convertScaleAbs(diff, alpha=10.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  def analyze_image(img_input):
61
- if img_input is None: return None, "โŒ Erreur : Image manquante"
62
 
63
- # 1. Prรฉparation (RGBA vers RGB)
64
- img = cv2.cvtColor(img_input, cv2.COLOR_RGBA2RGB) if img_input.shape[2] == 4 else img_input.copy()
 
 
 
 
 
 
 
65
 
66
- # 2. Correction Gamma pour images sombres (ton amรฉlioration spรฉcifique)
67
- mean_bright = np.mean(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY))
68
- if mean_bright < 60:
69
- table = np.array([((i / 255.0) ** (1.0/0.6)) * 255 for i in np.arange(0, 256)]).astype("uint8")
70
- img_for_analysis = cv2.LUT(img, table)
71
- light_msg = f"๐ŸŒ™ Mode Sombre (Luminositรฉ: {mean_bright:.1f})"
 
72
  else:
73
- img_for_analysis = img.copy()
74
  light_msg = "โ˜€๏ธ Luminositรฉ Standard"
75
 
76
- # 3. Lancement des outils Forensic
77
- noise_val, noise_map = analyze_sensor_noise(img_for_analysis)
78
- grid_s, fft_v = detect_grid_and_ringing(img_for_analysis)
79
- ela_s, ela_v = error_level_analysis(img_for_analysis)
80
 
81
- # 4. Calcul du score final pondรฉrรฉ
82
- score = 0
83
- reasons = []
84
- if grid_s > 15:
85
- score += 40
86
- reasons.append("โš ๏ธ Signatures structurelles GAN dรฉtectรฉes")
87
- if noise_val < 2.5:
88
- score += 30
89
- reasons.append("โšก Absence de grain de capteur naturel (Texture trop lisse)")
90
- if ela_s < 1.0:
91
- score += 20
92
- reasons.append("โš ๏ธ Profil de compression suspect")
93
-
94
- # 5. Visualisation
95
  fig, axes = plt.subplots(2, 2, figsize=(12, 10))
96
- axes[0,0].imshow(img); axes[0,0].set_title(f'Original ({light_msg})')
97
- axes[0,1].imshow(fft_v); axes[0,1].set_title('FFT (Filtre JPEG actif)')
98
- axes[1,0].imshow(ela_v); axes[1,0].set_title('ELA (Compression)')
99
- axes[1,1].imshow(noise_map, cmap='gray'); axes[1,1].set_title('Sensor Noise Pattern')
 
 
 
 
100
  for ax in axes.flatten(): ax.axis('off')
101
  plt.tight_layout()
102
-
103
- report = f"๐Ÿ›ก๏ธ MEDIASHIELD REPORT\nVerdict : {'PROBABLE IA' if score > 50 else 'AUTHENTIQUE'}\nScore : {score}/100\n\n" + ("\n".join(reasons) if reasons else "โœ… Aucun indicateur d'IA dรฉtectรฉ.")
104
  return fig, report
105
 
106
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
107
  # ๐ŸŽจ INTERFACE GRADIO
108
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
109
 
110
- with gr.Blocks(title="MediaShield PRO") as demo:
111
- gr.Markdown("# ๐Ÿ›ก๏ธ MediaShield PRO v2.2\nSami Meddeb - Digital Cooperation Association (ACoNum)")
112
  with gr.Row():
113
  with gr.Column():
114
- input_img = gr.Image(label="Image ร  analyser", type="numpy")
115
- btn = gr.Button("๐Ÿ” ANALYSER", variant="primary")
116
  with gr.Column():
117
  out_plot = gr.Plot()
118
- out_txt = gr.Textbox(label="Rapport Forensic", lines=10)
 
119
  btn.click(analyze_image, inputs=input_img, outputs=[out_plot, out_txt])
120
 
121
  if __name__ == "__main__":
 
5
  from scipy import ndimage
6
 
7
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
8
+ # ๐Ÿ”ฌ MEDIASHIELD PRO v2.1 โ€“ AVEC CORRECTION LUMIรˆRE
9
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
10
 
11
+ def analyze_chrominance_noise(img):
12
+ """Dรฉtecte l'uniformitรฉ anormale du bruit chromatique."""
13
+ ycrcb = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)
14
+ cr = ycrcb[:, :, 1].astype(np.float32)
15
+ cb = ycrcb[:, :, 2].astype(np.float32)
16
+
17
+ cr_var = ndimage.generic_filter(cr, np.var, size=5)
18
+ cb_var = ndimage.generic_filter(cb, np.var, size=5)
19
+
20
+ uniformity_cr = np.std(cr_var) / (np.mean(cr_var) + 1e-8)
21
+ uniformity_cb = np.std(cb_var) / (np.mean(cb_var) + 1e-8)
22
+
23
+ return (uniformity_cr + uniformity_cb) / 2, cr_var
24
 
25
+ def find_peaks(signal, threshold_factor=0.3):
 
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
+ sign_changes = np.sum(diff[1:] * diff[:-1] < 0)
44
+ return sign_changes / len(radial_profile)
45
+
46
  def detect_grid_and_ringing(img):
 
47
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype(np.float32)
48
  f = np.fft.fft2(gray)
49
  fshift = np.fft.fftshift(f)
 
51
 
52
  rows, cols = gray.shape
53
  crow, ccol = rows//2, cols//2
54
+ mask_radius = min(rows, cols) // 6
 
 
55
  y, x = np.ogrid[:rows, :cols]
56
+ mask = (x - ccol)**2 + (y - crow)**2 <= mask_radius**2
57
+ magnitude[mask] = 0
58
 
 
59
  proj_x = np.sum(magnitude, axis=0)
60
  proj_y = np.sum(magnitude, axis=1)
61
+ grid_score = (len(find_peaks(proj_x, 0.2)) + len(find_peaks(proj_y, 0.2))) / 2
62
+
63
+ radial = compute_radial_profile(magnitude)
64
+ ringing = detect_ringing(radial)
65
 
66
  fft_vis = np.log(magnitude + 1)
67
  fft_vis = (fft_vis - fft_vis.min()) / (fft_vis.max() - fft_vis.min() + 1e-8) * 255
68
+ fft_vis = cv2.applyColorMap(fft_vis.astype(np.uint8), cv2.COLORMAP_VIRIDIS)
69
+
70
+ return grid_score, ringing, fft_vis
71
 
72
+ def error_level_analysis(img, quality=85):
 
73
  encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
74
  _, enc = cv2.imencode('.jpg', cv2.cvtColor(img, cv2.COLOR_RGB2BGR), encode_param)
75
  dec = cv2.imdecode(enc, 1)
76
+ dec_rgb = cv2.cvtColor(dec, cv2.COLOR_BGR2RGB)
77
+ diff = cv2.absdiff(img, dec_rgb)
78
+ ela_enhanced = cv2.convertScaleAbs(diff, alpha=5.0)
79
+ return np.mean(diff), ela_enhanced
80
+
81
+ def compute_ai_score(metrics):
82
+ score = 0
83
+ reasons = []
84
+
85
+ if metrics['grid_score'] > 15:
86
+ score += 30
87
+ reasons.append("โš ๏ธ Strong grid patterns (GAN signature)")
88
+ if metrics['ringing'] > 0.25:
89
+ score += 25
90
+ reasons.append("โš ๏ธ Circular artifacts (Diffusion signature)")
91
+ if metrics['chrom_uniformity'] < 1.0:
92
+ score += 20
93
+ reasons.append("โšก Unnatural chrominance noise")
94
+ if metrics['ela_score'] < 1.5:
95
+ score += 15
96
+ reasons.append("โš ๏ธ Suspicious compression history")
97
+
98
+ return min(score, 100), reasons
99
+
100
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
101
+ # ๐ŸŽฏ FONCTION ANALYSE (AVEC GESTION IMAGES SOMBRES)
102
+ # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
103
 
104
  def analyze_image(img_input):
105
+ if img_input is None: return None, "Erreur"
106
 
107
+ # 1. Nettoyage format
108
+ if img_input.shape[2] == 4:
109
+ img = cv2.cvtColor(img_input, cv2.COLOR_RGBA2RGB)
110
+ else:
111
+ img = img_input.copy()
112
+
113
+ # 2. Correction Gamma pour images sombres
114
+ gray_check = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
115
+ mean_brightness = np.mean(gray_check)
116
 
117
+ # Image pour l'analyse (plus claire si besoin)
118
+ if mean_brightness < 60:
119
+ gamma = 0.6
120
+ invGamma = 1.0 / gamma
121
+ table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
122
+ img_analysed = cv2.LUT(img, table)
123
+ light_msg = f"๐ŸŒ™ Mode Sombre Activรฉ (Luminositรฉ: {mean_brightness:.1f})"
124
  else:
125
+ img_analysed = img.copy()
126
  light_msg = "โ˜€๏ธ Luminositรฉ Standard"
127
 
128
+ # 3. Traitement forensic sur l'image corrigรฉe
129
+ chrom_u, chrom_v = analyze_chrominance_noise(img_analysed)
130
+ grid_s, ring, fft_v = detect_grid_and_ringing(img_analysed)
131
+ ela_s, ela_v = error_level_analysis(img_analysed)
132
 
133
+ metrics = {
134
+ 'chrom_uniformity': chrom_u, 'grid_score': grid_s,
135
+ 'ringing': ring, 'ela_score': ela_s
136
+ }
137
+
138
+ ai_score, reasons = compute_ai_score(metrics)
139
+
140
+ # Visualisation
 
 
 
 
 
 
141
  fig, axes = plt.subplots(2, 2, figsize=(12, 10))
142
+ axes[0,0].imshow(img) # On montre l'originale
143
+ axes[0,0].set_title(f'๐Ÿ“ธ Original ({light_msg})')
144
+ axes[0,1].imshow(fft_v)
145
+ axes[0,1].set_title('๐Ÿ”ฎ FFT Frequency')
146
+ axes[1,0].imshow(ela_v)
147
+ axes[1,0].set_title('๐Ÿ” ELA Analysis')
148
+ axes[1,1].imshow(chrom_v, cmap='hot')
149
+ axes[1,1].set_title('๐ŸŒˆ Chrominance Noise')
150
  for ax in axes.flatten(): ax.axis('off')
151
  plt.tight_layout()
152
+
153
+ report = f"MEDIASHIELD REPORT\nScore: {ai_score}/100\n{light_msg}\n\nIndicateurs:\n" + "\n".join(reasons)
154
  return fig, report
155
 
156
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
157
  # ๐ŸŽจ INTERFACE GRADIO
158
  # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
159
 
160
+ with gr.Blocks() as demo:
161
+ gr.Markdown("# ๐Ÿ›ก๏ธ MediaShield PRO v2.1")
162
  with gr.Row():
163
  with gr.Column():
164
+ input_img = gr.Image(label="Image", type="numpy")
165
+ btn = gr.Button("ANALYSER", variant="primary")
166
  with gr.Column():
167
  out_plot = gr.Plot()
168
+ out_txt = gr.Textbox(label="Rapport", lines=10)
169
+
170
  btn.click(analyze_image, inputs=input_img, outputs=[out_plot, out_txt])
171
 
172
  if __name__ == "__main__":