AllMark / app.py
NeeravS's picture
Update app.py
269547c verified
raw
history blame
4.54 kB
import os
import subprocess
import importlib.util
import gradio as gr
import logging
from moviepy.editor import VideoFileClip
# Function to truncate video to 15 seconds
def truncate_video(video_file):
"""Truncates video to 15 seconds and saves it as a temporary file."""
clip = VideoFileClip(video_file)
truncated_clip = clip.subclip(0, min(15, clip.duration))
truncated_video_file = "temp_truncated_video.mp4"
truncated_clip.write_videofile(truncated_video_file, codec="libx264", audio_codec="aac")
return truncated_video_file
# Clone the GitHub repository containing the backend
def clone_repo():
"""Clone the GitHub repository containing the backend."""
repo_url = "https://github.com/NeeravSood/AllMark-MVP.git" # Update if necessary
repo_path = "./repository"
# Retrieve the GitHub Personal Access Token (GITHUB_PAT) from environment variables
github_pat = os.getenv("GITHUB_PAT")
if not github_pat:
raise RuntimeError("GitHub Personal Access Token (GITHUB_PAT) not found in environment variables.")
# Modify the repository URL to include the token for authentication
authenticated_repo_url = f"https://{github_pat}@github.com/NeeravSood/AllMark-MVP.git"
if os.path.exists(repo_path):
print("Repository already cloned.")
else:
try:
# Clone the repository using the authenticated URL
subprocess.run(
["git", "clone", authenticated_repo_url, repo_path],
check=True,
text=True,
capture_output=True
)
print("Repository cloned successfully.")
except subprocess.CalledProcessError as e:
print("Output:", e.stdout)
print("Error:", e.stderr)
raise RuntimeError(f"Failed to clone repository: {e.stderr}")
def import_backend_script(script_name):
"""Dynamically import the backend script."""
try:
script_path = os.path.join("./repository", script_name)
if not os.path.exists(script_path):
raise FileNotFoundError(f"Script {script_name} not found in the repository.")
spec = importlib.util.spec_from_file_location("backend_module", script_path)
backend_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(backend_module)
return backend_module
except Exception as e:
logging.error(f"Error importing backend script: {str(e)}")
raise RuntimeError(f"Failed to import backend script: {str(e)}")
# Clone the repository and import the backend module
clone_repo()
backend = import_backend_script("app.py") # Import app.py from the cloned repository
# Initialize the analyzer instance from the imported module
analyzer = backend.DeepfakeAnalyzer() # Use the imported module's class or function
# Define the Gradio function to analyze the video
def analyze_video(video_file):
# Truncate the video to 15 seconds
truncated_video = truncate_video(video_file)
# Pass the truncated video to the analyzer
results = analyzer.analyze_media(truncated_video)
# Get the combined assessment probability
combined_probability = results['combined_assessment']
# Interpret the result as genuine or deepfake based on probability threshold
if combined_probability < 50:
analysis_result = "genuine/original"
else:
analysis_result = "a deepfake"
# Create a readable output message
output_text = (
f"According to our analysis, the video you uploaded appears to be {analysis_result} "
f"with a {combined_probability:.2f}% probability. "
f"{len(results['video_analysis']['frame_results'])} frames were analyzed in total."
)
return output_text
# Define the Gradio interface with a text output for readability
interface = gr.Interface(
fn=analyze_video,
inputs=gr.Video(label="Upload Video"),
outputs="text",
title="AllMark - Deepfake Analyzer",
description="Upload a video to analyze for deepfake content. Get an assessment of the likelihood that the video is genuine or a deepfake."
)
# Define the Gradio interface
interface = gr.Interface(
fn=analyze_video,
inputs=gr.Video(label="Upload Video"),
outputs="json",
title="AllMark - Deepfake Analyzer",
description="Upload a video to analyze for deepfake content. N.B. - Average processing time is between 1 to 5 minutes."
)
# Launch Gradio app
if __name__ == "__main__":
interface.launch()