Spaces:
Sleeping
Sleeping
File size: 8,841 Bytes
251a307 12b9074 251a307 12b9074 e76944f 12b9074 e76944f 12b9074 e76944f 12b9074 e76944f 12b9074 e76944f 251a307 12b9074 251a307 573e322 12b9074 573e322 12b9074 573e322 12b9074 573e322 12b9074 573e322 251a307 573e322 251a307 573e322 251a307 573e322 251a307 12b9074 251a307 12b9074 251a307 12b9074 251a307 573e322 251a307 573e322 251a307 573e322 251a307 12b9074 251a307 12b9074 251a307 12b9074 251a307 573e322 251a307 573e322 251a307 573e322 251a307 12b9074 251a307 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.applications.efficientnet_v2 import preprocess_input
from transformers import AutoModelForAudioClassification, AutoFeatureExtractor
import torch
import librosa
from PIL import Image
import numpy as np
import cv2
import io
import os
import base64
import tempfile
# ==========================================
# 1. INITIAL SETUP
# ==========================================
app = FastAPI(title="Veritas Forensic Engine")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- GLOBAL VARIABLES ---
IMAGE_MODEL_PATH = "with_flux_model.keras"
AUDIO_MODEL_ID = "MelodyMachine/Deepfake-audio-detection-V2"
image_model = None
audio_model = None
feature_extractor = None
# ==========================================
# 2. STARTUP EVENT (Loads BOTH Models)
# ==========================================
@app.on_event("startup")
async def startup_event():
global image_model, audio_model, feature_extractor
# A. Load Image Model
if os.path.exists(IMAGE_MODEL_PATH):
print("π· Loading Image/Video Model...")
image_model = load_model(IMAGE_MODEL_PATH, compile=False)
print("β
Image Model Ready.")
else:
print(f"β CRITICAL: {IMAGE_MODEL_PATH} not found.")
# B. Load Audio Model
print("π€ Loading Audio Model (Wav2Vec2)...")
try:
feature_extractor = AutoFeatureExtractor.from_pretrained(AUDIO_MODEL_ID)
audio_model = AutoModelForAudioClassification.from_pretrained(AUDIO_MODEL_ID)
print("β
Audio Model Ready.")
except Exception as e:
print(f"β Audio Model Failed: {e}")
# ==========================================
# 3. HELPER FUNCTIONS (Image/GradCAM)
# ==========================================
def preprocess_image_array(img_array):
img_resized = tf.image.resize(img_array, (224, 224), method='lanczos3')
img_expanded = tf.expand_dims(img_resized, axis=0)
return preprocess_input(img_expanded)
def generate_heatmap_safe(img_tensor, pred_index):
try:
target_layer = None
for layer in image_model.layers:
if "efficientnet" in layer.name or "top_activation" in layer.name:
target_layer = layer
break
if not target_layer: return None
grad_model = tf.keras.models.Model(
[image_model.inputs],
[target_layer.output, image_model.output]
)
with tf.GradientTape() as tape:
last_conv_layer_output, preds = grad_model(img_tensor)
class_channel = preds[:, pred_index]
grads = tape.gradient(class_channel, last_conv_layer_output)
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
last_conv_layer_output = last_conv_layer_output[0]
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
heatmap = tf.squeeze(heatmap)
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
return heatmap.numpy()
except Exception as e:
print(f"β οΈ GradCAM Skipped: {e}")
return None
def overlay_heatmap(original_img_pil, heatmap):
img = np.array(original_img_pil)
if heatmap is None:
is_success, buffer = cv2.imencode(".jpg", cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
return base64.b64encode(buffer).decode("utf-8")
heatmap = np.uint8(255 * heatmap)
jet = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
jet = cv2.resize(jet, (img.shape[1], img.shape[0]))
superimposed_img = jet * 0.4 + img * 0.6
superimposed_img = np.clip(superimposed_img, 0, 255).astype("uint8")
is_success, buffer = cv2.imencode(".jpg", cv2.cvtColor(superimposed_img, cv2.COLOR_RGB2BGR))
return base64.b64encode(buffer).decode("utf-8")
# ==========================================
# 4. ENDPOINT: IMAGE ANALYSIS
# ==========================================
@app.post("/api/analyze-image")
async def analyze_image(file: UploadFile = File(...)):
if not image_model: raise HTTPException(500, "Image model not loaded.")
try:
contents = await file.read()
img = Image.open(io.BytesIO(contents)).convert('RGB')
processed_tensor = preprocess_image_array(np.array(img))
preds = image_model.predict(processed_tensor)
ai_score = float(preds[0][0])
real_score = float(preds[0][1])
confidence = max(ai_score, real_score) * 100
label = "AI" if ai_score > real_score else "Real"
pred_index = 0 if ai_score > real_score else 1
heatmap = generate_heatmap_safe(processed_tensor, pred_index)
heatmap_b64 = overlay_heatmap(img, heatmap)
return {
"type": "image",
"prediction": label,
"confidence": round(confidence, 2),
"heatmap_base64": heatmap_b64,
"probabilities": {"ai": ai_score, "real": real_score}
}
except Exception as e:
return {"error": str(e)}
# ==========================================
# 5. ENDPOINT: VIDEO ANALYSIS
# ==========================================
@app.post("/api/analyze-video")
async def analyze_video(file: UploadFile = File(...)):
if not image_model: raise HTTPException(500, "Image model not loaded.")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_vid:
temp_vid.write(await file.read())
temp_path = temp_vid.name
cap = cv2.VideoCapture(temp_path)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
frames_to_analyze = 10
step = max(1, frame_count // frames_to_analyze)
timeline_results = []
fake_frame_count = 0
for i in range(0, frame_count, step):
cap.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame = cap.read()
if not ret: break
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
processed_tensor = preprocess_image_array(frame_rgb)
preds = image_model.predict(processed_tensor)
ai_score = float(preds[0][0])
timestamp = round(i / fps, 2) if fps > 0 else 0
timeline_results.append({
"timestamp": timestamp,
"ai_score": ai_score,
"status": "FAKE" if ai_score > 0.5 else "REAL"
})
if ai_score > 0.5: fake_frame_count += 1
if len(timeline_results) >= frames_to_analyze: break
cap.release()
os.unlink(temp_path)
overall_fake_percent = (fake_frame_count / len(timeline_results)) * 100 if len(timeline_results) > 0 else 0
final_verdict = "DEEPFAKE DETECTED" if overall_fake_percent > 40 else "AUTHENTIC VIDEO"
return {
"type": "video",
"prediction": final_verdict,
"fake_percentage": round(overall_fake_percent, 2),
"timeline": timeline_results
}
except Exception as e:
return {"error": str(e)}
# ==========================================
# 6. ENDPOINT: AUDIO ANALYSIS
# ==========================================
@app.post("/api/analyze-audio")
async def analyze_audio(file: UploadFile = File(...)):
if not audio_model: raise HTTPException(500, "Audio model not loaded.")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_audio:
temp_audio.write(await file.read())
temp_path = temp_audio.name
audio_input, sample_rate = librosa.load(temp_path, sr=16000)
inputs = feature_extractor(audio_input, sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
logits = audio_model(**inputs).logits
probs = torch.nn.functional.softmax(logits, dim=-1)
# --- FIXED MAPPING FOR MELODY MACHINE V2 ---
# Label 0 is usually REAL, Label 1 is usually FAKE/SPOOF
real_score = float(probs[0][0])
fake_score = float(probs[0][1])
os.unlink(temp_path)
verdict = "FAKE AUDIO DETECTED" if fake_score > real_score else "AUTHENTIC AUDIO"
confidence = max(fake_score, real_score) * 100
return {
"type": "audio",
"prediction": verdict,
"confidence": round(confidence, 2),
"probabilities": {"ai": fake_score, "real": real_score}
}
except Exception as e:
return {"error": str(e)} |