File size: 4,784 Bytes
3a3c2be
2dc47c6
 
cb82c24
2dc47c6
615dea5
0ef1091
82731b4
589bf82
9b30919
 
773a0e8
dae402a
 
 
 
 
 
773a0e8
589bf82
 
 
 
 
 
7884a81
2dc47c6
9b30919
2dc47c6
3a3c2be
2dc47c6
 
 
 
cb82c24
2dc47c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1534cde
2dc47c6
 
 
 
8cb4ac6
2dc47c6
 
 
 
 
 
 
 
1534cde
2dc47c6
8cb4ac6
514b638
1ae13cc
82731b4
8cb4ac6
9b30919
 
 
 
7b57752
7c400e9
 
 
 
564bb7d
cc2ac2b
 
 
 
 
 
 
 
 
 
 
f755699
cc2ac2b
 
 
 
 
 
 
 
136897a
cc2ac2b
1ae13cc
cc2ac2b
136897a
cc2ac2b
 
136897a
1ae13cc
 
7b57752
 
 
1ae13cc
b2619fa
564bb7d
136897a
cc2ac2b
8cb4ac6
 
9b30919
8cb4ac6
5520756
216b41c
8cb4ac6
cb82c24
 
1534cde
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
import os
import subprocess
import importlib.util
import gradio as gr
import logging
#from moviepy.editor import VideoFileClip
import torch
#import spaces

ACCESS_KEY = os.getenv("ACCESS_KEY")

'''
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False


def truncate_video(video_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
'''
def clone_repo():
    repo_url = "https://github.com/NeeravSood/AllMark-MVP.git"
    repo_path = "./repository"

    github_pat = os.getenv("GITHUB_PAT")
    if not github_pat:
        raise RuntimeError("GitHub Personal Access Token (GITHUB_PAT) not found in environment variables.")
    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:
            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)}")

# Run repository setup and model import
clone_repo()
backend = import_backend_script("app.py") 
analyzer = backend.DeepfakeAnalyzer()

#@spaces.GPU(duration=3000)
def analyze_video(video_file):
    if ACCESS_KEY is None:
        logging.error("Access key not set in environment variables.")
        return {"error": "Server misconfiguration. Access key not set."}

    try:
        #truncated_video = truncate_video(video_file)  # Truncate the video for faster analysis
        #results = analyzer.analyze_media(truncated_video)
        results = analyzer.analyze_media(video_file)


        # Extract frame count and video probability
        frame_count = len(results['video_analysis']['frame_results'])
        video_probability = results['video_analysis']['probability']
        combined_assessment = results.get('combined_assessment', "Inconclusive")

        # Reapply combined_results logic for front-end clarity
        if frame_count < 300:
            assessment = "Inconclusive due to lack of sufficient frames"
        elif frame_count < 500:
            threshold = 0.4
            assessment = "Deepfake" if video_probability >= threshold else "Genuine"
        else:
            threshold = 0.5
            assessment = "Deepfake" if video_probability >= threshold else "Genuine"

        # Construct output message
        message = (
            f"According to our analysis, the video you uploaded appears to be {assessment}. "
            f"{frame_count} frames were analyzed in total."
        )

        # Return the final output
        output = {
            "message": message,
            "details": {
                "video_probability": video_probability,
                "combined_assessment": assessment  # Final assessment based on reapplied logic
            }
        }
        return output

    except Exception as e:
        logging.error(f"Error during analysis: {e}")
        return {"error": "An error occurred during video analysis. Please check your input and try again."}




interface = gr.Interface(
    fn=analyze_video,
    inputs=gr.Video(label="Upload Video"),
    outputs="json",
    title="AllMark - Deepfake and AI Video Analyzer",
    description="Upload a MP4 video for analysis. Multiple model iterations are being tested, so results are slow and may vary for the same video. Our Models 2 and 3 shall be available on AWS."
)

if __name__ == "__main__":
    interface.launch()