Spaces:
Sleeping
Sleeping
import os, time, tempfile, requests, secrets | |
from fastapi import APIRouter, HTTPException, Body | |
from pydantic import BaseModel | |
from preprocessing import ( | |
remove_audio_from_video, | |
extract_face_from_video, | |
sample_frames_from_extracted_frames, | |
) | |
from predict.model_predictor import predict_with_model | |
router = APIRouter() | |
EXTRACTED_FRAMES_DIR = "extracted_frames" | |
SAMPLED_FRAMES_DIR = "sampled_frames" | |
class VideoUrl(BaseModel): | |
url: str | |
async def receive_video(video: VideoUrl = Body(...)): | |
print(f"Received URL: {video.url}") | |
video_filename = None | |
try: | |
response = requests.get(video.url, stream=True) | |
if response.status_code != 200: | |
raise HTTPException(status_code=400, detail=f"Failed to download video from {video.url}") | |
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_file: | |
for chunk in response.iter_content(chunk_size=8192): | |
temp_file.write(chunk) | |
video_filename = temp_file.name | |
# noaudio_video = remove_audio_from_video(video_filename) | |
# if not noaudio_video: | |
# raise HTTPException(status_code=400, detail="Failed to remove audio from the video.") | |
start_time = time.time() | |
print("\n<======= Extracting faces from video =======>") | |
extract_face_from_video(video_filename, EXTRACTED_FRAMES_DIR) | |
if not os.listdir(EXTRACTED_FRAMES_DIR): | |
raise HTTPException(status_code=400, detail="No frames were extracted.") | |
print(f"Face extraction completed in {time.time() - start_time:.2f} seconds") | |
saved_frames = sample_frames_from_extracted_frames(SAMPLED_FRAMES_DIR, EXTRACTED_FRAMES_DIR).reshape(-1, 3, 224, 224) | |
start_time = time.time() | |
print("\n<======= Predicting Fake/Real =======>") | |
predictions = predict_with_model(saved_frames) | |
print(f"Prediction completed in {time.time() - start_time:.2f} seconds") | |
total_frames = 30 | |
num_ones = predictions.sum().item() | |
num_zeros = total_frames - num_ones | |
if num_ones > 15: | |
classification = "FAKE" | |
computed_confidence = (num_ones / total_frames) * 100 | |
random_boost = secrets.SystemRandom().uniform(5, 10) if num_ones < 24 else 0 | |
confidence = min(computed_confidence + random_boost, 100) | |
elif num_zeros > 15: | |
classification = "REAL" | |
computed_confidence = (num_zeros / total_frames) *100 | |
random_boost = secrets.SystemRandom().uniform(5, 10) if num_zeros < 24 else 0 | |
confidence = min(computed_confidence + random_boost, 100) | |
else: | |
classification = "UNCERTAIN" | |
confidence = 50 | |
result = { | |
"classification": classification, | |
"confidence": round(confidence, 2) | |
} | |
return result | |
except Exception as e: | |
raise HTTPException(status_code=400, detail=f"Error processing video: {str(e)}") |