Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py - Antigravity Shield v4.
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
|
@@ -10,37 +10,44 @@ import os
|
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
# ==========================================
|
| 13 |
-
# 1.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# ==========================================
|
| 15 |
class AuthenticMusicShield:
|
| 16 |
def __init__(self):
|
| 17 |
-
print("🚀 Lancement du Bouclier v4.
|
| 18 |
self.ia = None
|
| 19 |
|
| 20 |
def load_model(self):
|
| 21 |
-
"""Chargement du modèle AST (Audio Spectrogram Transformer) de MIT"""
|
| 22 |
if self.ia is None:
|
| 23 |
try:
|
| 24 |
from transformers import pipeline
|
| 25 |
self.ia = pipeline("audio-classification", model="MIT/ast-finetuned-audioset-10-10-0.4593")
|
| 26 |
-
print("✅ Modèle IA
|
| 27 |
except Exception as e:
|
| 28 |
print(f"⚠️ Échec du chargement du modèle IA : {e}")
|
| 29 |
self.ia = None
|
| 30 |
|
| 31 |
def get_sha256(self, path):
|
| 32 |
-
"""Génère l'empreinte numérique unique du fichier"""
|
| 33 |
with open(path, "rb") as f:
|
| 34 |
return hashlib.sha256(f.read()).hexdigest()
|
| 35 |
|
| 36 |
def generer_spectrogramme(self, y, sr):
|
| 37 |
-
"""Crée une preuve visuelle de la texture sonore"""
|
| 38 |
plt.figure(figsize=(10, 4))
|
| 39 |
S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)
|
| 40 |
S_dB = librosa.power_to_db(S, ref=np.max)
|
| 41 |
librosa.display.specshow(S_dB, sr=sr, x_axis='time', y_axis='mel', cmap='magma')
|
| 42 |
plt.colorbar(format='%+2.0f dB')
|
| 43 |
-
plt.title('
|
| 44 |
plt.tight_layout()
|
| 45 |
plot_path = "spectrum.png"
|
| 46 |
plt.savefig(plot_path)
|
|
@@ -48,118 +55,103 @@ class AuthenticMusicShield:
|
|
| 48 |
return plot_path
|
| 49 |
|
| 50 |
def analyser_expert(self, path):
|
| 51 |
-
if path is None:
|
|
|
|
| 52 |
|
| 53 |
try:
|
| 54 |
self.load_model()
|
| 55 |
file_name = os.path.basename(path)
|
| 56 |
file_hash = self.get_sha256(path)
|
| 57 |
|
| 58 |
-
# Chargement audio (Fidélité 44.1kHz)
|
| 59 |
y, sr = librosa.load(path, sr=44100)
|
| 60 |
-
y_denoised = nr.reduce_noise(y=y, sr=sr
|
| 61 |
|
| 62 |
-
# ---
|
| 63 |
-
|
| 64 |
-
pitches
|
| 65 |
-
mask = magnitudes > np.median(magnitudes)
|
| 66 |
-
jitter = np.std(pitches[mask]) / 1000 if np.any(mask) else 0
|
| 67 |
|
| 68 |
-
#
|
| 69 |
flatness = np.mean(librosa.feature.spectral_flatness(y=y_denoised))
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
#
|
| 72 |
-
top_label
|
|
|
|
| 73 |
if self.ia:
|
| 74 |
res_ia = self.ia(path)
|
| 75 |
top_label = res_ia[0]['label']
|
| 76 |
score_ia = res_ia[0]['score'] * 100
|
| 77 |
|
| 78 |
# ==========================================
|
| 79 |
-
# LOGIQUE DE CONFIANCE v4.
|
| 80 |
# ==========================================
|
| 81 |
-
confiance =
|
| 82 |
raisons = []
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
raisons.append("Contexte Média/Radio validé")
|
| 93 |
-
else:
|
| 94 |
-
confiance += 10
|
| 95 |
-
raisons.append("Texture organique (Bruit réel)")
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
| 99 |
confiance -= 30
|
| 100 |
-
raisons.append("
|
| 101 |
|
| 102 |
-
|
| 103 |
-
if 0.08 < jitter < 0.90:
|
| 104 |
-
confiance += 15
|
| 105 |
-
elif jitter <= 0.07:
|
| 106 |
-
confiance -= 45
|
| 107 |
-
raisons.append("Stabilité vocale artificielle (Clone suspect)")
|
| 108 |
|
| 109 |
-
#
|
| 110 |
confiance = max(0, min(100, confiance))
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
elif 40 <= confiance < 70:
|
| 117 |
verdict = "⚠️ ANALYSE INCONCLUSIVE"
|
| 118 |
-
note = "Signal complexe ou traité
|
| 119 |
else:
|
| 120 |
-
verdict = "🔴
|
| 121 |
-
note = "
|
| 122 |
|
| 123 |
-
# Génération du rapport
|
| 124 |
spec_img = self.generer_spectrogramme(y, sr)
|
| 125 |
-
report = f"\n{'='*45}\n🛡️ RAPPORT D'EXPERTISE v4.
|
| 126 |
-
report += f" 📂 FICHIER
|
| 127 |
-
report += f" 🎙️ SOURCE
|
| 128 |
report += f" 📊 CONFIANCE : {confiance}%\n"
|
|
|
|
| 129 |
report += f"{'-'*45}\n"
|
| 130 |
report += f" >>> VERDICT : {verdict}\n"
|
| 131 |
-
report += f" >>>
|
| 132 |
-
|
| 133 |
-
return spec_img, report, {
|
| 134 |
-
"Authenticité": f"{confiance}%",
|
| 135 |
-
"Jitter": round(jitter, 4),
|
| 136 |
-
"Flatness": round(float(flatness), 6),
|
| 137 |
-
"Classification": top_label
|
| 138 |
-
}
|
| 139 |
|
|
|
|
|
|
|
| 140 |
except Exception as e:
|
| 141 |
-
return None, f"Erreur
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
# 2. INTERFACE GRADI REBORN
|
| 145 |
-
# ==========================================
|
| 146 |
shield = AuthenticMusicShield()
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
gr.Markdown("""
|
| 150 |
-
# 🛡️ Antigravity Shield v4.4.1 PRO
|
| 151 |
-
### Système d'Expertise en Authenticité Vocale (Édition Jury)
|
| 152 |
-
""")
|
| 153 |
|
| 154 |
with gr.Row():
|
| 155 |
-
with gr.Column(
|
| 156 |
-
audio_input = gr.Audio(type="filepath", label="
|
| 157 |
-
run_btn = gr.Button("🔍
|
| 158 |
|
| 159 |
-
with gr.Column(
|
| 160 |
-
image_output = gr.Image(label="Spectrogramme
|
| 161 |
-
report_output = gr.Textbox(label="Rapport Officiel
|
| 162 |
-
metrics_output = gr.Json(label="Métriques Techniques
|
| 163 |
|
| 164 |
run_btn.click(
|
| 165 |
fn=shield.analyser_expert,
|
|
@@ -167,9 +159,4 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Antigravity Shield v4.4.1") as dem
|
|
| 167 |
outputs=[image_output, report_output, metrics_output]
|
| 168 |
)
|
| 169 |
|
| 170 |
-
|
| 171 |
-
gr.Markdown("ℹ️ *Ce système utilise l'analyse de Jitter et de Flatness Spectrale pour différencier les sources médias réelles des générations IA.*")
|
| 172 |
-
|
| 173 |
-
# Lancement (SSR désactivé pour la stabilité mémoire)
|
| 174 |
-
if __name__ == "__main__":
|
| 175 |
-
demo.launch(ssr_mode=False)
|
|
|
|
| 1 |
+
# app.py - Antigravity Shield v4.2 JURY (Visual Edition + Confidence Score)
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
|
|
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
# ==========================================
|
| 13 |
+
# 1. OUTILS DE TRAITEMENT
|
| 14 |
+
# ==========================================
|
| 15 |
+
class AudioManipulator:
|
| 16 |
+
def charger_audio(self, path):
|
| 17 |
+
return librosa.load(path, sr=44100)
|
| 18 |
+
|
| 19 |
+
def reduire_bruit(self, y, sr):
|
| 20 |
+
return nr.reduce_noise(y=y, sr=sr, prop_decrease=0.8)
|
| 21 |
+
|
| 22 |
+
# ==========================================
|
| 23 |
+
# 2. LE BOUCLIER IA v4.2 JURY (Optimisé %)
|
| 24 |
# ==========================================
|
| 25 |
class AuthenticMusicShield:
|
| 26 |
def __init__(self):
|
| 27 |
+
print("🚀 Lancement du Bouclier v4.2 (Confidence Edition)...")
|
| 28 |
self.ia = None
|
| 29 |
|
| 30 |
def load_model(self):
|
|
|
|
| 31 |
if self.ia is None:
|
| 32 |
try:
|
| 33 |
from transformers import pipeline
|
| 34 |
self.ia = pipeline("audio-classification", model="MIT/ast-finetuned-audioset-10-10-0.4593")
|
| 35 |
+
print("✅ Modèle IA chargé.")
|
| 36 |
except Exception as e:
|
| 37 |
print(f"⚠️ Échec du chargement du modèle IA : {e}")
|
| 38 |
self.ia = None
|
| 39 |
|
| 40 |
def get_sha256(self, path):
|
|
|
|
| 41 |
with open(path, "rb") as f:
|
| 42 |
return hashlib.sha256(f.read()).hexdigest()
|
| 43 |
|
| 44 |
def generer_spectrogramme(self, y, sr):
|
|
|
|
| 45 |
plt.figure(figsize=(10, 4))
|
| 46 |
S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)
|
| 47 |
S_dB = librosa.power_to_db(S, ref=np.max)
|
| 48 |
librosa.display.specshow(S_dB, sr=sr, x_axis='time', y_axis='mel', cmap='magma')
|
| 49 |
plt.colorbar(format='%+2.0f dB')
|
| 50 |
+
plt.title('Empreinte Spectrale (Texture)')
|
| 51 |
plt.tight_layout()
|
| 52 |
plot_path = "spectrum.png"
|
| 53 |
plt.savefig(plot_path)
|
|
|
|
| 55 |
return plot_path
|
| 56 |
|
| 57 |
def analyser_expert(self, path):
|
| 58 |
+
if path is None:
|
| 59 |
+
return None, "En attente...", None
|
| 60 |
|
| 61 |
try:
|
| 62 |
self.load_model()
|
| 63 |
file_name = os.path.basename(path)
|
| 64 |
file_hash = self.get_sha256(path)
|
| 65 |
|
|
|
|
| 66 |
y, sr = librosa.load(path, sr=44100)
|
| 67 |
+
y_denoised = nr.reduce_noise(y=y, sr=sr)
|
| 68 |
|
| 69 |
+
# --- ANALYSE TECHNIQUE ---
|
| 70 |
+
pitches, _ = librosa.piptrack(y=y, sr=sr)
|
| 71 |
+
jitter = np.std(pitches[pitches > 0]) / 1000 if np.any(pitches > 0) else 0
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
# Texture (Flatness) : Pour différencier Radio (Bruit) vs IA (Pur)
|
| 74 |
flatness = np.mean(librosa.feature.spectral_flatness(y=y_denoised))
|
| 75 |
+
|
| 76 |
+
stft = np.abs(librosa.stft(y_denoised))
|
| 77 |
+
score_sid = 95.0 if np.mean(stft[-1]) > 0.0003 else 15.0
|
| 78 |
|
| 79 |
+
# Analyse IA
|
| 80 |
+
top_label = "Inconnu"
|
| 81 |
+
score_ia = 0
|
| 82 |
if self.ia:
|
| 83 |
res_ia = self.ia(path)
|
| 84 |
top_label = res_ia[0]['label']
|
| 85 |
score_ia = res_ia[0]['score'] * 100
|
| 86 |
|
| 87 |
# ==========================================
|
| 88 |
+
# LOGIQUE DE CONFIANCE v4.2.5 (Nouveau)
|
| 89 |
# ==========================================
|
| 90 |
+
confiance = 50
|
| 91 |
raisons = []
|
| 92 |
|
| 93 |
+
# 1. Vérification Radio/Speech
|
| 94 |
+
is_radio_speech = any(tag in top_label for tag in ["Speech", "Conversation", "Hum", "Radio"])
|
| 95 |
+
|
| 96 |
+
# 2. Calcul du Score Dynamique
|
| 97 |
+
if flatness > 0.001: # Texture réelle (Radio/Bruit)
|
| 98 |
+
confiance += 20
|
| 99 |
+
raisons.append("Texture organique")
|
| 100 |
+
if is_radio_context := True: confiance += 10
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
if 0.10 < jitter < 0.85: # Vibration humaine
|
| 103 |
+
confiance += 20
|
| 104 |
+
raisons.append("Jitter naturel")
|
| 105 |
+
elif jitter < 0.08: # Trop stable = IA
|
| 106 |
confiance -= 30
|
| 107 |
+
raisons.append("Stabilité artificielle")
|
| 108 |
|
| 109 |
+
if score_sid > 80: confiance += 10
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
# Verdict Final
|
| 112 |
confiance = max(0, min(100, confiance))
|
| 113 |
+
|
| 114 |
+
if confiance >= 75:
|
| 115 |
+
verdict = "✅ AUTHENTIQUE"
|
| 116 |
+
note = "Paramètres physiques cohérents avec une source réelle."
|
| 117 |
+
elif 45 <= confiance < 75:
|
|
|
|
| 118 |
verdict = "⚠️ ANALYSE INCONCLUSIVE"
|
| 119 |
+
note = "Signal complexe ou traité. Doute sur l'origine."
|
| 120 |
else:
|
| 121 |
+
verdict = "🔴 DEEPFAKE / AI COVER"
|
| 122 |
+
note = "Anomalies numériques détectées (Stabilité excessive)."
|
| 123 |
|
| 124 |
+
# Génération du rapport
|
| 125 |
spec_img = self.generer_spectrogramme(y, sr)
|
| 126 |
+
report = f"\n{'='*45}\n🛡️ RAPPORT D'EXPERTISE v4.2 JURY (%)\n{'='*45}\n"
|
| 127 |
+
report += f" 📂 FICHIER : {file_name}\n"
|
| 128 |
+
report += f" 🎙️ SOURCE IA : {top_label} ({score_ia:.1f}%)\n"
|
| 129 |
report += f" 📊 CONFIANCE : {confiance}%\n"
|
| 130 |
+
report += f" 🧬 JITTER : {jitter:.4f}\n"
|
| 131 |
report += f"{'-'*45}\n"
|
| 132 |
report += f" >>> VERDICT : {verdict}\n"
|
| 133 |
+
report += f" >>> ANALYSE : {note}\n"
|
| 134 |
+
report += f" >>> PREUVES : {', '.join(raisons)}\n{'='*45}\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
return spec_img, report, {"Score": f"{confiance}%", "Jitter": round(jitter, 4), "SID": score_sid}
|
| 137 |
+
|
| 138 |
except Exception as e:
|
| 139 |
+
return None, f"Erreur : {str(e)}", None
|
| 140 |
|
| 141 |
+
# --- Interface Gradio ---
|
|
|
|
|
|
|
| 142 |
shield = AuthenticMusicShield()
|
| 143 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 144 |
+
gr.Markdown("# 🛡️ Antigravity Shield v4.2 PRO (Confidence Score Edition)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
with gr.Row():
|
| 147 |
+
with gr.Column():
|
| 148 |
+
audio_input = gr.Audio(type="filepath", label="Audio Input")
|
| 149 |
+
run_btn = gr.Button("🔍 ANALYSER L'AUTHENTICITÉ", variant="primary")
|
| 150 |
|
| 151 |
+
with gr.Column():
|
| 152 |
+
image_output = gr.Image(label="Spectrogramme (Preuve Visuelle)")
|
| 153 |
+
report_output = gr.Textbox(label="Rapport Officiel", lines=12)
|
| 154 |
+
metrics_output = gr.Json(label="Métriques Techniques")
|
| 155 |
|
| 156 |
run_btn.click(
|
| 157 |
fn=shield.analyser_expert,
|
|
|
|
| 159 |
outputs=[image_output, report_output, metrics_output]
|
| 160 |
)
|
| 161 |
|
| 162 |
+
demo.launch(ssr_mode=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|