NOBODY204 commited on
Commit
7c40cfb
·
verified ·
1 Parent(s): e6b8a32

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +453 -329
app.py CHANGED
@@ -1,345 +1,469 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- analyze_media.pyPont Python AI pour MAM SHIELD v5.2
4
- ACoNum / Trusted Sound 2026
5
  =====================================================
6
- Usage (appelé par server.js) :
7
- python analyze_media.py audio <chemin_fichier>
8
- python analyze_media.py video <chemin_fichier>
9
- python analyze_media.py image <chemin_fichier>
10
- python analyze_media.py pdf <chemin_fichier>
11
-
12
- Retourne un JSON sur stdout :
13
- { "summary": "...", "tags": [...], "transcript": "...", "flac_ok": true, "flac_path": "..." }
14
  """
15
 
16
- import sys
 
 
 
 
 
17
  import os
18
  import json
19
  import subprocess
20
- import traceback
21
-
22
- # ── Config Ollama ────────────────────────────────────────────
23
- OLLAMA_HOST = 'http://localhost:11434'
24
- OLLAMA_MODEL = 'qwen2.5:3b' # tags + résumé standard
25
-
26
- # ── Nemotron auto-détection au démarrage ───────────────
27
- # Modèle téléchargé : nvidia/Nemotron-3-Nano-Omni-30B → version 4B locale
28
- # Nom Ollama attendu : nemotron-mini ou nemotron-mini:4b
29
- NEMOTRON_MODEL = None
30
- NEMOTRON_PRIORITY = [ # ordre de priorité exact
31
- 'nemotron-mini:4b',
32
- 'nemotron-mini:latest',
33
- 'nemotron-mini',
34
- 'nemotron:4b',
35
- 'nemotron:mini',
36
- 'nemotron:latest',
37
- 'nvidia/nemotron-mini',
38
- 'nemotron-nano',
39
- 'nemotron',
40
- ]
41
-
42
- def detect_nemotron():
43
- """Cherche automatiquement un modèle Nemotron dans Ollama (priorité 4B mini)."""
44
- global NEMOTRON_MODEL
45
- try:
46
- import urllib.request as ur
47
- req = ur.Request(OLLAMA_HOST + '/api/tags', method='GET')
48
- with ur.urlopen(req, timeout=5) as r:
49
- data = json.loads(r.read().decode('utf-8'))
50
- models = [m.get('name','') for m in data.get('models', [])]
51
- # Cherche par priorité exacte d'abord
52
- for prio in NEMOTRON_PRIORITY:
53
- if prio in models:
54
- NEMOTRON_MODEL = prio
55
- return prio
56
- # Sinon: correspondance partielle
57
- for m in models:
58
- if 'nemotron' in m.lower():
59
- NEMOTRON_MODEL = m
60
- return m
61
- except Exception:
62
- pass
63
- NEMOTRON_MODEL = OLLAMA_MODEL # fallback qwen si absent
64
- return NEMOTRON_MODEL
65
-
66
- detect_nemotron()
67
-
68
- # ── Config FFmpeg ────────────────────────────────────────────
69
- def find_ffmpeg():
70
- candidates = [
71
- os.path.join(os.path.expanduser('~'), 'ffmpeg', 'bin', 'ffmpeg.exe'),
72
- os.path.join(os.path.expanduser('~'), 'AppData', 'Local', 'Programs', 'ffmpeg', 'bin', 'ffmpeg.exe'),
73
- 'ffmpeg',
74
- ]
75
- for c in candidates:
76
- if c == 'ffmpeg':
77
- return c
78
- if os.path.exists(c):
79
- return c
80
- return 'ffmpeg'
81
-
82
- FFMPEG = find_ffmpeg()
83
-
84
- # ── Résultat ─────────────────────────────────────────────────
85
- def ok(**kwargs):
86
- print(json.dumps({ 'ok': True, **kwargs }, ensure_ascii=False))
87
- sys.exit(0)
88
-
89
- def fail(msg):
90
- print(json.dumps({ 'ok': False, 'error': str(msg) }, ensure_ascii=False))
91
- sys.exit(1)
92
-
93
-
94
- # ════════════════════════════════════════════════════════════
95
- # OLLAMA appel local
96
- # ════════════════════════════════════════════════════════════
97
- def ollama_generate(prompt, model=OLLAMA_MODEL):
98
- try:
99
- import urllib.request
100
- body = json.dumps({
101
- 'model': model,
102
- 'prompt': prompt,
103
- 'stream': False,
104
- 'options': { 'temperature': 0, 'num_predict': 300 }
105
- }).encode('utf-8')
106
- req = urllib.request.Request(
107
- OLLAMA_HOST + '/api/generate',
108
- data=body,
109
- headers={ 'Content-Type': 'application/json' },
110
- method='POST'
111
- )
112
- with urllib.request.urlopen(req, timeout=30) as resp:
113
- data = json.loads(resp.read().decode('utf-8'))
114
- return data.get('response', '').strip()
115
- except Exception as e:
116
- return None
117
-
118
-
119
- def generate_tags(name, media_type, content=''):
120
- raw = ollama_generate(
121
- f"Tu es un archiviste média. Génère exactement 5 tags pertinents pour cet asset.\n"
122
- f"Nom: {name}\nType: {media_type}\nContenu: {content[:300] if content else 'non disponible'}\n"
123
- f"Réponds UNIQUEMENT avec un tableau JSON de 5 strings en français. "
124
- f"Ex: [\"tag1\",\"tag2\",\"tag3\",\"tag4\",\"tag5\"]"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  )
126
- if not raw:
127
- return []
128
- try:
129
- import re
130
- m = re.search(r'\[.*?\]', raw, re.DOTALL)
131
- return json.loads(m.group(0)) if m else []
132
- except Exception:
133
- return []
134
-
135
-
136
- def generate_summary(name, media_type, content=''):
137
- return ollama_generate(
138
- f"Tu es un archiviste média professionnel. Rédige une description courte (2-3 phrases) pour:\n"
139
- f"Nom: {name}\nType: {media_type}\nContenu: {content[:500] if content else 'non disponible'}\n"
140
- f"Réponds uniquement avec la description en français."
141
  )
142
 
 
 
143
 
144
- # ════════════════════════════════════════════════════════════
145
- # AUDIO — Whisper + conversion FLAC TC-04
146
- # ════════════════════════════════════════════════════════════
147
- def analyze_audio(file_path):
148
- transcript = ''
149
- flac_ok = False
150
- flac_path = ''
151
-
152
- # 1. Transcription Whisper
153
- try:
154
- import whisper
155
- model = whisper.load_model('small')
156
- result = model.transcribe(file_path, language=None, fp16=False)
157
- transcript = result.get('text', '').strip()
158
- except ImportError:
159
- transcript = '[Whisper non installé — lance INSTALLER_MAM.bat]'
160
- except Exception as e:
161
- transcript = f'[Erreur Whisper: {str(e)[:100]}]'
162
-
163
- # 2. Conversion FLAC IASA TC-04 (96kHz / 24-bit)
164
- try:
165
- base = os.path.splitext(os.path.basename(file_path))[0]
166
- flac_dir = os.path.join(os.path.dirname(file_path), '..', 'flac')
167
- os.makedirs(flac_dir, exist_ok=True)
168
- flac_path = os.path.abspath(os.path.join(flac_dir, base + '_TC04_96k24b.flac'))
169
-
170
- cmd = [
171
- FFMPEG, '-y', '-i', file_path,
172
- '-c:a', 'flac',
173
- '-ar', '96000',
174
- '-sample_fmt', 's32',
175
- '-bits_per_raw_sample', '24',
176
- '-compression_level', '8',
177
- flac_path
178
- ]
179
- result = subprocess.run(cmd, capture_output=True, timeout=120)
180
- flac_ok = result.returncode == 0 and os.path.exists(flac_path)
181
- except Exception as e:
182
- flac_ok = False
183
- flac_path = ''
184
-
185
- # 3. Tags + résumé via Ollama
186
- name = os.path.basename(file_path)
187
- content = transcript[:400] if transcript else ''
188
- tags = generate_tags(name, 'audio', content)
189
- summary = generate_summary(name, 'audio', content)
190
-
191
- ok(
192
- summary = summary or f'Fichier audio : {name}',
193
- tags = tags or ['audio', 'archive', 'patrimoine', 'son', 'ACoNum'],
194
- transcript = transcript,
195
- flac_ok = flac_ok,
196
- flac_path = flac_path,
197
- standard = 'IASA TC-04 — FLAC 96kHz/24-bit' if flac_ok else 'Conversion FLAC non effectuée',
198
- )
199
-
200
-
201
- # ════════════════════════════════════════════════════════════
202
- # VIDEO — FFmpeg + Whisper
203
- # ════════════════════════════════════════════════════════════
204
- def analyze_video(file_path):
205
- transcript = ''
206
- audio_tmp = file_path + '_audio_tmp.wav'
207
-
208
- # 1. Extraire l'audio en WAV
209
- try:
210
- cmd = [FFMPEG, '-y', '-i', file_path, '-vn',
211
- '-ar', '16000', '-ac', '1', '-f', 'wav', audio_tmp]
212
- subprocess.run(cmd, capture_output=True, timeout=120)
213
- except Exception:
214
- pass
215
-
216
- # 2. Transcrire avec Whisper
217
- audio_src = audio_tmp if os.path.exists(audio_tmp) else file_path
218
- try:
219
- import whisper
220
- model = whisper.load_model('small')
221
- result = model.transcribe(audio_src, language=None, fp16=False)
222
- transcript = result.get('text', '').strip()
223
- except ImportError:
224
- transcript = '[Whisper non installé]'
225
- except Exception as e:
226
- transcript = f'[Erreur Whisper: {str(e)[:100]}]'
227
-
228
- # Nettoyage fichier temporaire
229
- if os.path.exists(audio_tmp):
230
- try: os.remove(audio_tmp)
231
- except: pass
232
-
233
- name = os.path.basename(file_path)
234
- content = transcript[:400]
235
- tags = generate_tags(name, 'video', content)
236
- summary = generate_summary(name, 'video', content)
237
-
238
- ok(
239
- summary = summary or f'Fichier vidéo : {name}',
240
- tags = tags or ['video', 'archive', 'media', 'ACoNum', 'deepfake'],
241
- transcript = transcript,
242
- videoshield_url = 'https://huggingface.co/spaces/NOBODY204/VideoShield',
243
- )
244
-
245
-
246
- # ════════════════════════════════════════════════════════════
247
- # IMAGE — LLaVA via Ollama (si disponible)
248
- # ════════════════════════════════════════════════════════════
249
- def analyze_image(file_path):
250
- description = ''
251
- name = os.path.basename(file_path)
252
-
253
- # Tenter LLaVA via Ollama (modèle vision)
254
- try:
255
- import urllib.request, base64
256
- with open(file_path, 'rb') as f:
257
- img_b64 = base64.b64encode(f.read()).decode('utf-8')
258
-
259
- body = json.dumps({
260
- 'model': 'llava:7b',
261
- 'prompt': 'Décris cette image en français en 2-3 phrases pour un archiviste média.',
262
- 'images': [img_b64],
263
- 'stream': False,
264
- 'options': { 'temperature': 0, 'num_predict': 200 }
265
- }).encode('utf-8')
266
-
267
- req = urllib.request.Request(
268
- OLLAMA_HOST + '/api/generate',
269
- data=body,
270
- headers={ 'Content-Type': 'application/json' },
271
- method='POST'
272
- )
273
- with urllib.request.urlopen(req, timeout=60) as resp:
274
- data = json.loads(resp.read().decode('utf-8'))
275
- description = data.get('response', '').strip()
276
- except Exception:
277
- description = f'[LLaVA non disponible — analyse visuelle désactivée pour {name}]'
278
-
279
- tags = generate_tags(name, 'image', description)
280
- summary = description or generate_summary(name, 'image', '')
281
-
282
- ok(
283
- summary = summary or f'Fichier image : {name}',
284
- tags = tags or ['image', 'visuel', 'archive', 'media', 'ACoNum'],
285
- description = description,
286
- imageshield_url = 'https://huggingface.co/spaces/NOBODY204/ImageShield',
287
- )
288
-
289
-
290
- # ���═══════════════════════════════════════════════════════════
291
- # PDF — pdfplumber
292
- # ════════════════════════════════════════════════════════════
293
- def analyze_pdf(file_path):
294
- text = ''
295
- name = os.path.basename(file_path)
296
-
297
- try:
298
- import pdfplumber
299
- with pdfplumber.open(file_path) as pdf:
300
- pages = []
301
- for i, page in enumerate(pdf.pages[:5]): # 5 premières pages max
302
- t = page.extract_text()
303
- if t:
304
- pages.append(t.strip())
305
- text = '\n'.join(pages)
306
- except ImportError:
307
- text = '[pdfplumber non installé — lance INSTALLER_MAM.bat]'
308
- except Exception as e:
309
- text = f'[Erreur lecture PDF: {str(e)[:100]}]'
310
-
311
- content = text[:600]
312
- tags = generate_tags(name, 'pdf', content)
313
- summary = generate_summary(name, 'pdf', content)
314
-
315
- ok(
316
- summary = summary or f'Document PDF : {name}',
317
- tags = tags or ['document', 'pdf', 'archive', 'texte', 'ACoNum'],
318
- text = text[:1000] if text else '',
319
- )
320
-
321
-
322
- # ════════════════════════════════════════════════════════════
323
- # MAIN
324
- # ════════════════════════════════════════════════════════════
325
- if __name__ == '__main__':
326
- if len(sys.argv) < 3:
327
- fail('Usage: python analyze_media.py <audio|video|image|pdf> <chemin_fichier>')
328
-
329
- media_type = sys.argv[1].lower().strip()
330
- file_path = sys.argv[2].strip()
331
-
332
- if not os.path.exists(file_path):
333
- fail(f'Fichier introuvable : {file_path}')
334
 
335
- try:
336
- if media_type == 'audio': analyze_audio(file_path)
337
- elif media_type == 'video': analyze_video(file_path)
338
- elif media_type == 'image': analyze_image(file_path)
339
- elif media_type in ('pdf', 'doc'): analyze_pdf(file_path)
340
- else: fail(f'Type non supporté : {media_type}. Utiliser audio/video/image/pdf')
341
- except Exception as e:
342
- fail(traceback.format_exc())
343
 
344
 
345
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ Antigravity Shield v5.0ACoNum / Trusted Sound 2026
 
4
  =====================================================
5
+ Fusion : AASIST neural anti-spoofing + Jitter/Flatness + AcoustID
6
+ Résout :
7
+ - Faux positifs sur anciennes chansons (vintage)
8
+ - Voix off / parlées non chantées
9
+ - AI Cover complexes (ElevenLabs, YourTTS, RVC)
10
+ - Broadcast FM (jitter élevé naturel)
 
 
11
  """
12
 
13
+ import numpy as np
14
+ import librosa
15
+ import librosa.display
16
+ import matplotlib.pyplot as plt
17
+ import noisereduce as nr
18
+ import hashlib
19
  import os
20
  import json
21
  import subprocess
22
+ import gradio as gr
23
+
24
+ # ══════════════════════════════════════════════════════════════
25
+ # CONFIG
26
+ # ══════════════════════════════════════════════════════════════
27
+
28
+ # AcoustIDclé API (remplacer par la tienne)
29
+ ACOUSTID_KEY = "TY6HUQsigs"
30
+
31
+ # AASIST — modèle HuggingFace anti-spoofing
32
+ AASIST_MODEL_ID = "Mahmoud-Yassen/aasist-antispoof" # fallback si absent: "m-aliabbas/AASIST"
33
+
34
+ # Double Jitter — seuils v4.4.5 calibrés broadcast FM
35
+ JITTER_BROADCAST_MIN = 0.85
36
+ FLATNESS_THRESHOLD = 0.0012
37
+ FLATNESS_BROADCAST = 0.0010
38
+ CENTROID_BROADCAST = 3500.0
39
+ CENTROID_VINTAGE = 3000.0
40
+ ZCR_VINTAGE = 0.06
41
+
42
+
43
+ # ══════════════════════════════════════════════════════════════
44
+ class AntigravityShield:
45
+ def __init__(self):
46
+ print("🚀 Antigravity Shield v5.0 — AASIST + Jitter + AcoustID")
47
+ self.ast_model = None # MIT/ast — classification audio générale
48
+ self.aasist = None # AASIST — anti-spoofing neural
49
+ self.aasist_ok = False
50
+
51
+ # ──────────────────────────────────────────────────────────
52
+ # MODÈLES
53
+ # ──────────────────────────────────────────────────────────
54
+ def load_ast(self):
55
+ if self.ast_model is None:
56
+ try:
57
+ from transformers import pipeline
58
+ self.ast_model = pipeline(
59
+ "audio-classification",
60
+ model="MIT/ast-finetuned-audioset-10-10-0.4593"
61
+ )
62
+ print("✅ AST chargé")
63
+ except Exception as e:
64
+ print(f"⚠️ AST non disponible : {e}")
65
+ self.ast_model = None
66
+
67
+ def load_aasist(self):
68
+ """
69
+ Charge AASIST pour la détection anti-spoofing de bas niveau.
70
+ AASIST opère sur la forme d'onde brute → détecte les artefacts
71
+ que le jitter seul ne voit pas (TTS modernes, RVC, ElevenLabs).
72
+ """
73
+ if self.aasist is None:
74
+ try:
75
+ from transformers import pipeline, AutoFeatureExtractor, AutoModelForAudioClassification
76
+ import torch
77
+ # Essayer plusieurs modèles anti-spoofing disponibles
78
+ candidates = [
79
+ "Mahmoud-Yassen/aasist-antispoof",
80
+ "m-aliabbas/AASIST",
81
+ "fusing/aasist",
82
+ ]
83
+ for model_id in candidates:
84
+ try:
85
+ self.aasist = pipeline(
86
+ "audio-classification",
87
+ model=model_id,
88
+ sampling_rate=16000
89
+ )
90
+ self.aasist_ok = True
91
+ print(f"✅ AASIST chargé : {model_id}")
92
+ break
93
+ except Exception:
94
+ continue
95
+ if not self.aasist_ok:
96
+ print("⚠️ AASIST non disponible — mode fallback jitter seul")
97
+ except Exception as e:
98
+ print(f"⚠️ AASIST erreur : {e}")
99
+
100
+ # ──────────────────────────────────────────────────────────
101
+ # SHA256
102
+ # ──────────────────────────────────────────────────────────
103
+ def get_sha256(self, path):
104
+ with open(path, "rb") as f:
105
+ return hashlib.sha256(f.read()).hexdigest()
106
+
107
+ # ──────────────────────────────────────────────────────────
108
+ # ACOUSTID — identification musicale
109
+ # ──────────────────────────────────────────────────────────
110
+ def acoustid_lookup(self, path):
111
+ """
112
+ Identifie le fichier via AcoustID/MusicBrainz.
113
+ Si la chanson est CONNUE → c'est une vraie chanson (bonus authenticité).
114
+ Si la chanson n'est PAS dans la base → potentiellement AI Cover.
115
+ """
116
+ try:
117
+ import acoustid
118
+ results = acoustid.match(ACOUSTID_KEY, path)
119
+ for score, recording_id, title, artist in results:
120
+ if score > 0.8:
121
+ return True, f"{artist} — {title} (score {score:.0%})", recording_id
122
+ return False, "Non identifié dans MusicBrainz", None
123
+ except ImportError:
124
+ # Fallback: fpcalc si acoustid module absent
125
+ try:
126
+ fpcalc = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fpcalc.exe')
127
+ if not os.path.exists(fpcalc):
128
+ fpcalc = 'fpcalc'
129
+ result = subprocess.run(
130
+ [fpcalc, '-json', path],
131
+ capture_output=True, timeout=15
132
+ )
133
+ if result.returncode == 0:
134
+ data = json.loads(result.stdout.decode('utf-8'))
135
+ fingerprint = data.get('fingerprint', '')
136
+ return bool(fingerprint), f"Empreinte : {fingerprint[:24]}...", None
137
+ except Exception:
138
+ pass
139
+ return None, "AcoustID non disponible", None
140
+ except Exception as e:
141
+ return None, f"AcoustID erreur : {str(e)[:60]}", None
142
+
143
+ # ──────────────────────────────────────────────────────────
144
+ # SPECTROGRAMME
145
+ # ──────────────────────────────────────────────────────────
146
+ def generer_spectrogramme(self, y, sr, jitter_a, jitter_b, aasist_score):
147
+ fig, axes = plt.subplots(1, 2, figsize=(14, 4))
148
+
149
+ # Mel spectrogram
150
+ S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128)
151
+ S_dB = librosa.power_to_db(S, ref=np.max)
152
+ librosa.display.specshow(S_dB, sr=sr, x_axis='time', y_axis='mel',
153
+ cmap='magma', ax=axes[0])
154
+ axes[0].set_title('Mel Spectrogram — Texture vocale')
155
+
156
+ # Double Jitter timeline
157
+ frame_len = 2048
158
+ hop = 512
159
+ pitches, mags = librosa.piptrack(y=y, sr=sr, hop_length=hop, fmin=60, fmax=4000)
160
+ frames = np.arange(pitches.shape[1])
161
+ times = librosa.frames_to_time(frames, sr=sr, hop_length=hop)
162
+
163
+ # Jitter par frame
164
+ jitter_timeline = []
165
+ for i in range(pitches.shape[1]):
166
+ col = pitches[:, i]
167
+ col_mags = mags[:, i]
168
+ m = col_mags > np.median(col_mags)
169
+ jitter_timeline.append(np.std(col[m]) / 1000 if np.any(m) else 0)
170
+
171
+ axes[1].plot(times[:len(jitter_timeline)], jitter_timeline,
172
+ color='cyan', linewidth=0.8, alpha=0.8, label='Jitter frame')
173
+ axes[1].axhline(y=jitter_a, color='lime', linestyle='--', linewidth=1.5,
174
+ label=f'Jitter-A global={jitter_a:.3f}')
175
+ axes[1].axhline(y=jitter_b, color='yellow', linestyle='--', linewidth=1.5,
176
+ label=f'Jitter-B débruité={jitter_b:.3f}')
177
+ if aasist_score is not None:
178
+ axes[1].axhline(y=aasist_score, color='red', linestyle=':', linewidth=2,
179
+ label=f'AASIST spoof={aasist_score:.2f}')
180
+ axes[1].set_xlabel('Temps (s)')
181
+ axes[1].set_ylabel('Jitter')
182
+ axes[1].set_title('Double Jitter + AASIST Timeline')
183
+ axes[1].legend(fontsize=7)
184
+ axes[1].set_ylim(0, max(2.0, max(jitter_timeline) * 1.2) if jitter_timeline else 2.0)
185
+
186
+ plt.tight_layout()
187
+ plot_path = "spectrum_v5.png"
188
+ plt.savefig(plot_path, dpi=120)
189
+ plt.close()
190
+ return plot_path
191
+
192
+ # ──────────────────────────────────────────────────────────
193
+ # ANALYSE AASIST — neural anti-spoofing
194
+ # ──────────────────────────────────────────────────────────
195
+ def run_aasist(self, path):
196
+ """
197
+ Retourne (spoof_score 0-1, label_string)
198
+ spoof_score > 0.5 = suspect de spoofing
199
+ """
200
+ if not self.aasist_ok or self.aasist is None:
201
+ return None, "AASIST non chargé"
202
+ try:
203
+ results = self.aasist(path)
204
+ # Cherche le label "spoof" ou "fake"
205
+ for r in results:
206
+ lbl = r['label'].lower()
207
+ if any(k in lbl for k in ['spoof', 'fake', 'synthetic', 'generated']):
208
+ return float(r['score']), f"AASIST spoof={r['score']:.1%}"
209
+ # Si labels sont 0/1 ou bonafide/spoof
210
+ for r in results:
211
+ lbl = r['label'].lower()
212
+ if any(k in lbl for k in ['1', 'spoof']):
213
+ return float(r['score']), f"AASIST score={r['score']:.1%}"
214
+ # Retour du premier label
215
+ return 1 - float(results[0]['score']), f"AASIST={results[0]['label']}:{results[0]['score']:.1%}"
216
+ except Exception as e:
217
+ return None, f"AASIST erreur : {str(e)[:60]}"
218
+
219
+ # ──────────────────────────────────────────────────────────
220
+ # ANALYSE PRINCIPALE
221
+ # ──────────────────────────────────────────────────────────
222
+ def analyser_expert(self, path):
223
+ if path is None:
224
+ return None, "En attente...", None
225
+ try:
226
+ self.load_ast()
227
+ self.load_aasist()
228
+
229
+ y, sr = librosa.load(path, sr=44100)
230
+
231
+ # ── DÉBRUITAGE ADAPTATIF ──────────────────────────
232
+ y_light = nr.reduce_noise(y=y, sr=sr, prop_decrease=0.3)
233
+ centroid_light = float(np.mean(librosa.feature.spectral_centroid(y=y_light, sr=sr)))
234
+
235
+ if centroid_light < CENTROID_BROADCAST:
236
+ prop = 0.4
237
+ raison_denoise = "Débruitage doux (broadcast détecté)"
238
+ else:
239
+ prop = 0.7
240
+ raison_denoise = "Débruitage standard"
241
+
242
+ y_denoised = nr.reduce_noise(y=y, sr=sr, prop_decrease=prop)
243
+
244
+ # ── DOUBLE JITTER (A brut / B débruité) ──────────
245
+ def compute_jitter(signal):
246
+ pitches, mags = librosa.piptrack(y=signal, sr=sr, fmin=60, fmax=4000)
247
+ mask = mags > np.median(mags)
248
+ return float(np.std(pitches[mask]) / 1000) if np.any(mask) else 0.0
249
+
250
+ jitter_a = compute_jitter(y) # Jitter brut
251
+ jitter_b = compute_jitter(y_denoised) # Jitter débruité
252
+ jitter_delta = abs(jitter_a - jitter_b)
253
+
254
+ flatness = float(np.mean(librosa.feature.spectral_flatness(y=y_denoised)))
255
+ centroid = float(np.mean(librosa.feature.spectral_centroid(y=y_denoised, sr=sr)))
256
+ zcr = float(np.mean(librosa.feature.zero_crossing_rate(y_denoised)))
257
+
258
+ # ── VINTAGE ───────────────────────────────────────
259
+ is_vintage = centroid < CENTROID_VINTAGE and zcr < ZCR_VINTAGE
260
+
261
+ # ── AST CLASSIFICATION ────────────────────────────
262
+ top_label, score_ia = "Inconnu", 0.0
263
+ if self.ast_model:
264
+ try:
265
+ res_ia = self.ast_model(path)
266
+ top_label = res_ia[0]['label']
267
+ score_ia = res_ia[0]['score'] * 100
268
+ except Exception:
269
+ pass
270
+
271
+ # ── AASIST — neural anti-spoofing ─────────────────
272
+ aasist_score, aasist_label = self.run_aasist(path)
273
+
274
+ # ── ACOUSTID ──────────────────────────────────────
275
+ acoustid_known, acoustid_info, _ = self.acoustid_lookup(path)
276
+
277
+ # ══════════════════════════════════════════════════
278
+ # SCORING FUSIONNÉ v5.0
279
+ # Pondération : AASIST(40%) + Jitter(35%) + Flatness(15%) + Context(10%)
280
+ # ══════════════════════════════════════════════════
281
+ confiance = 50
282
+ raisons = []
283
+
284
+ # ── 1. AASIST NEURAL (priorité maximale) ──────────
285
+ if aasist_score is not None:
286
+ if aasist_score > 0.80:
287
+ # AASIST très sûr → deepfake
288
+ confiance -= 40
289
+ raisons.append(f"🤖 AASIST détecte synthèse ({aasist_score:.0%}) — deepfake probable")
290
+ elif aasist_score > 0.55:
291
+ confiance -= 20
292
+ raisons.append(f"⚠️ AASIST : signal suspect ({aasist_score:.0%})")
293
+ elif aasist_score < 0.30:
294
+ confiance += 20
295
+ raisons.append(f"✅ AASIST : signal authentique ({1-aasist_score:.0%} bona-fide)")
296
+ else:
297
+ raisons.append(f"📊 AASIST ambigu ({aasist_score:.0%})")
298
+ else:
299
+ raisons.append("⚙️ AASIST indisponible — mode jitter seul")
300
+
301
+ # ── 2. VINTAGE (override partiel si vintage) ──────
302
+ if is_vintage:
303
+ confiance += 12
304
+ raisons.append("����️ Signature vintage (enregistrement ancien)")
305
+ # Les AI Covers anciens ont rarement un centroïde aussi bas
306
+ if aasist_score and aasist_score > 0.80:
307
+ raisons.append("⚠️ Vintage MAIS AASIST détecte synthèse — AI Cover vintage possible")
308
+
309
+ # ── 3. FLATNESS ────────────────────────────────────
310
+ if flatness > FLATNESS_THRESHOLD:
311
+ confiance += 15
312
+ raisons.append(f"🌿 Texture organique (flatness={flatness:.5f})")
313
+ else:
314
+ confiance -= 20
315
+ raisons.append(f"🔇 Signal trop pur (flatness={flatness:.5f} < {FLATNESS_THRESHOLD})")
316
+ if score_ia < 70:
317
+ confiance -= 15
318
+ raisons.append("🚫 Signal pur + source IA incertaine → deepfake renforcé")
319
+
320
+ # ── 4. DOUBLE JITTER ───────────────────────────────
321
+ is_broadcast = (jitter_a >= JITTER_BROADCAST_MIN and centroid_light < CENTROID_BROADCAST) or prop == 0.4
322
+
323
+ # 4a. Voix/parole
324
+ if "Music" not in top_label and "Singing" not in top_label:
325
+ if 0.10 < jitter_b < 0.80:
326
+ confiance += 20
327
+ raisons.append(f"🗣️ Vibration vocale naturelle (jitter-B={jitter_b:.3f})")
328
+ elif jitter_b >= JITTER_BROADCAST_MIN:
329
+ if is_broadcast and flatness > FLATNESS_BROADCAST:
330
+ confiance += 18
331
+ raisons.append(f"📻 Jitter broadcast FM validé (jitter-B={jitter_b:.3f})")
332
+ elif is_broadcast and flatness <= FLATNESS_BROADCAST:
333
+ confiance -= 25
334
+ raisons.append(f"❌ Trop pur pour broadcast (jitter-B={jitter_b:.3f})")
335
+ elif flatness > 0.0008:
336
+ confiance += 12
337
+ raisons.append(f"📡 Flux radio détecté (jitter-B={jitter_b:.3f})")
338
+ else:
339
+ confiance -= 50
340
+ raisons.append(f"🚨 Instabilité artificielle voix off (jitter-B={jitter_b:.3f})")
341
+ # Jitter delta trop grand = débruitage anormal = synthétique
342
+ if jitter_delta > 0.5:
343
+ confiance -= 15
344
+ raisons.append(f"⚡ Delta jitter A-B anormal (Δ={jitter_delta:.3f}) — artefact synthèse")
345
+
346
+ # 4b. Musique / Chant
347
+ else:
348
+ if jitter_b > 1.0 or jitter_b < 0.09:
349
+ if is_vintage:
350
+ confiance += 8
351
+ raisons.append(f"🎵 Jitter vintage validé (jitter-B={jitter_b:.3f})")
352
+ elif flatness < FLATNESS_THRESHOLD:
353
+ confiance -= 50
354
+ raisons.append(f"🎤 AI Cover — jitter anormal + signal pur (jitter-B={jitter_b:.3f})")
355
+ else:
356
+ confiance -= 15
357
+ raisons.append(f"🔎 Jitter musical suspect — analyse inconclusif (jitter-B={jitter_b:.3f})")
358
+ else:
359
+ confiance += 18
360
+ raisons.append(f"🎶 Harmoniques naturelles validées (jitter-B={jitter_b:.3f})")
361
+
362
+ # ── 5. ACOUSTID ────────────────────────────────────
363
+ if acoustid_known is True:
364
+ confiance += 15
365
+ raisons.append(f"🎵 Chanson connue MusicBrainz : {acoustid_info}")
366
+ # Chanson connue MAIS AASIST détecte synthèse = AI Cover de chanson réelle
367
+ if aasist_score and aasist_score > 0.65:
368
+ confiance -= 20
369
+ raisons.append("🚨 Chanson connue + AASIST suspect = AI Cover d'original")
370
+ elif acoustid_known is False:
371
+ raisons.append(f"❓ Non identifié MusicBrainz — {acoustid_info}")
372
+ else:
373
+ raisons.append(f"⚙️ {acoustid_info}")
374
+
375
+ confiance = max(0, min(100, confiance))
376
+
377
+ # ── VERDICT ────────────────────────────────────────
378
+ if confiance >= 70:
379
+ verdict = "🔒 AUTHENTIQUE CERTIFIÉ"
380
+ color = "green"
381
+ elif 40 <= confiance < 70:
382
+ verdict = "⚠️ ANALYSE INCONCLUSIVE"
383
+ color = "orange"
384
+ else:
385
+ verdict = "🛑 AI COVER / DEEPFAKE DÉTECTÉ"
386
+ color = "red"
387
+
388
+ sha = self.get_sha256(path)
389
+
390
+ report = f"\n{'='*50}\n📌 RAPPORT Antigravity Shield v5.0\n{'='*50}\n"
391
+ report += f" 🤖 AST SOURCE : {top_label} ({score_ia:.1f}%)\n"
392
+ report += f" 🧠 AASIST : {aasist_label}\n"
393
+ report += f" 🎯 CONFIANCE : {confiance}%\n"
394
+ report += f" 🎛️ JITTER-A : {jitter_a:.4f} (brut)\n"
395
+ report += f" 🎛️ JITTER-B : {jitter_b:.4f} (débruité)\n"
396
+ report += f" ⚡ JITTER-Δ : {jitter_delta:.4f}\n"
397
+ report += f" 📊 FLATNESS : {flatness:.6f}\n"
398
+ report += f" 🕰️ VINTAGE : {'Oui' if is_vintage else 'Non'}\n"
399
+ report += f" 📻 BROADCAST : {'Oui' if is_broadcast else 'Non'}\n"
400
+ report += f" 🎵 ACOUSTID : {acoustid_info}\n"
401
+ report += f" 🧹 DÉBRUITAGE : {raison_denoise}\n"
402
+ report += f" 🔑 SHA256 : {sha[:24]}...\n"
403
+ report += f"{'-'*50}\n"
404
+ report += f" >>> VERDICT : {verdict}\n"
405
+ report += f" >>> NOTES :\n"
406
+ for r in raisons:
407
+ report += f" • {r}\n"
408
+ report += f"{'='*50}\n"
409
+ report += "Antigravity Shield v5.0 · ACoNum / Trusted Sound 2026\n"
410
+
411
+ return (
412
+ self.generer_spectrogramme(y, sr, jitter_a, jitter_b, aasist_score),
413
+ report,
414
+ {
415
+ "Score": f"{confiance}%",
416
+ "Verdict": verdict,
417
+ "Jitter-A": round(jitter_a, 4),
418
+ "Jitter-B": round(jitter_b, 4),
419
+ "Jitter-Delta": round(jitter_delta, 4),
420
+ "Flatness": round(flatness, 6),
421
+ "AASIST": round(aasist_score, 3) if aasist_score is not None else "N/A",
422
+ "AcoustID": acoustid_info,
423
+ "Vintage": is_vintage,
424
+ "Broadcast": is_broadcast,
425
+ "Centroid": round(centroid, 1)
426
+ }
427
+ )
428
+
429
+ except Exception as e:
430
+ import traceback
431
+ return None, f"Erreur : {e}\n{traceback.format_exc()}", None
432
+
433
+
434
+ # ══════════════════════════════════════════════════════════════
435
+ # INTERFACE GRADIO
436
+ # ══════════════════════════════════════════════════════════════
437
+ shield = AntigravityShield()
438
+
439
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
440
+ gr.Markdown(
441
+ "# 🛡️ Antigravity Shield v5.0 PRO\n"
442
+ "### Détecteur d'authenticité audio — AASIST + Double Jitter + AcoustID\n"
443
+ "_Fusion v5.0 : AASIST neural anti-spoofing + jitter calibré broadcast FM + AcoustID MusicBrainz_"
444
  )
445
+ with gr.Row():
446
+ with gr.Column():
447
+ audio_input = gr.Audio(type="filepath", label="Audio Input (MP3/WAV/FLAC)")
448
+ run_btn = gr.Button("⚙️ ANALYSER", variant="primary")
449
+ with gr.Column():
450
+ image_output = gr.Image(label="Spectrogramme + Double Jitter")
451
+ report_output = gr.Textbox(label="Rapport d'expertise", lines=20)
452
+ metrics_output = gr.JSON(label="Métriques détaillées")
453
+
454
+ run_btn.click(
455
+ fn=shield.analyser_expert,
456
+ inputs=audio_input,
457
+ outputs=[image_output, report_output, metrics_output]
 
 
458
  )
459
 
460
+ if __name__ == "__main__":
461
+ demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
462
 
463
+
464
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
 
466
+
 
 
 
 
 
 
 
467
 
468
 
469