NeeravS commited on
Commit
6853273
·
verified ·
1 Parent(s): f755699

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -12
app.py CHANGED
@@ -7,6 +7,11 @@ from moviepy.editor import VideoFileClip
7
  import json
8
  import spaces
9
  import torch
 
 
 
 
 
10
 
11
  torch.set_num_threads(1)
12
  torch.set_num_interop_threads(1)
@@ -16,17 +21,21 @@ torch.backends.cudnn.benchmark = False
16
  torch.backends.cuda.matmul.allow_tf32 = False
17
  torch.backends.cudnn.allow_tf32 = False
18
 
 
19
  def truncate_video(video_file):
20
  """Truncates video to 15 seconds and saves it as a temporary file."""
21
  clip = VideoFileClip(video_file)
22
  truncated_clip = clip.subclip(0, min(15, clip.duration))
23
  truncated_video_file = "temp_truncated_video.mp4"
24
  truncated_clip.write_videofile(truncated_video_file, codec="libx264", audio_codec="aac")
 
 
25
  return truncated_video_file
26
 
 
27
  def clone_repo():
28
  """Clone the GitHub repository containing the backend."""
29
- repo_url = "https://github.com/NeeravSood/AllMark-MVP.git" # Update when changing
30
  repo_path = "./repository"
31
 
32
  github_pat = os.getenv("GITHUB_PAT")
@@ -50,6 +59,7 @@ def clone_repo():
50
  print("Error:", e.stderr)
51
  raise RuntimeError(f"Failed to clone repository: {e.stderr}")
52
 
 
53
  def import_backend_script(script_name):
54
  """Dynamically import the backend script."""
55
  try:
@@ -65,24 +75,41 @@ def import_backend_script(script_name):
65
  logging.error(f"Error importing backend script: {str(e)}")
66
  raise RuntimeError(f"Failed to import backend script: {str(e)}")
67
 
 
68
  clone_repo()
69
- backend = import_backend_script("app.py")
70
  analyzer = backend.DeepfakeAnalyzer()
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  @spaces.GPU(duration=1000)
73
  def analyze_video(video_file):
74
  try:
 
75
  truncated_video = truncate_video(video_file)
76
  results = analyzer.analyze_media(truncated_video)
77
 
78
- # Get combined_assessment and handle non-numeric values
79
  combined_assessment = results.get('combined_assessment', 0)
80
  if isinstance(combined_assessment, str) and combined_assessment.lower() == "deepfake":
81
  analysis_result = "a deepfake"
82
  else:
83
  combined_assessment = int(combined_assessment) if str(combined_assessment).isdigit() else 0
84
  analysis_result = "genuine/original" if combined_assessment < 50 else "a deepfake"
85
-
86
  output = {
87
  "message": f"According to our analysis, the video you uploaded appears to be {analysis_result}. "
88
  f"{len(results['video_analysis']['frame_results'])} frames were analyzed in total."
@@ -93,14 +120,41 @@ def analyze_video(video_file):
93
  logging.error(f"Error during analysis: {e}")
94
  return {"error": "An error occurred during video analysis. Please check your input and try again."}
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- interface = gr.Interface(
98
- fn=analyze_video,
99
- inputs=gr.Video(label="Upload Video"),
100
- outputs="json",
101
- title="AllMark - Deepfake Analyzer",
102
- description="Upload a video to analyze. N.B. - Only mp4 files. Processing time 1-10 minutes. For any false negatives, please contact the publisher for verification. Incognito Mode Recommended"
103
- )
104
 
 
105
  if __name__ == "__main__":
106
- interface.launch()
 
7
  import json
8
  import spaces
9
  import torch
10
+ import random
11
+ import string
12
+
13
+ # Set up logging
14
+ logging.basicConfig(level=logging.ERROR)
15
 
16
  torch.set_num_threads(1)
17
  torch.set_num_interop_threads(1)
 
21
  torch.backends.cuda.matmul.allow_tf32 = False
22
  torch.backends.cudnn.allow_tf32 = False
23
 
24
+ # Function to truncate video
25
  def truncate_video(video_file):
26
  """Truncates video to 15 seconds and saves it as a temporary file."""
27
  clip = VideoFileClip(video_file)
28
  truncated_clip = clip.subclip(0, min(15, clip.duration))
29
  truncated_video_file = "temp_truncated_video.mp4"
30
  truncated_clip.write_videofile(truncated_video_file, codec="libx264", audio_codec="aac")
31
+ clip.close()
32
+ truncated_clip.close()
33
  return truncated_video_file
34
 
35
+ # Clone repository
36
  def clone_repo():
37
  """Clone the GitHub repository containing the backend."""
38
+ repo_url = "https://github.com/NeeravSood/AllMark-MVP.git"
39
  repo_path = "./repository"
40
 
41
  github_pat = os.getenv("GITHUB_PAT")
 
59
  print("Error:", e.stderr)
60
  raise RuntimeError(f"Failed to clone repository: {e.stderr}")
61
 
62
+ # Import backend script
63
  def import_backend_script(script_name):
64
  """Dynamically import the backend script."""
65
  try:
 
75
  logging.error(f"Error importing backend script: {str(e)}")
76
  raise RuntimeError(f"Failed to import backend script: {str(e)}")
77
 
78
+ # Clone and import repository
79
  clone_repo()
80
+ backend = import_backend_script("app.py")
81
  analyzer = backend.DeepfakeAnalyzer()
82
 
83
+ # Generate a random CAPTCHA challenge
84
+ def generate_captcha():
85
+ return ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
86
+
87
+ # Initial CAPTCHA
88
+ captcha_solution = generate_captcha()
89
+
90
+ def verify_captcha(user_input):
91
+ global captcha_solution
92
+ if user_input.strip() == captcha_solution:
93
+ return "Captcha verified. You can now upload a video.", True, captcha_solution
94
+ else:
95
+ captcha_solution = generate_captcha() # Reset CAPTCHA on failure
96
+ return f"Incorrect CAPTCHA. Please try again.", False, captcha_solution
97
+
98
  @spaces.GPU(duration=1000)
99
  def analyze_video(video_file):
100
  try:
101
+ # Video truncation and analysis
102
  truncated_video = truncate_video(video_file)
103
  results = analyzer.analyze_media(truncated_video)
104
 
105
+ # Process combined assessment
106
  combined_assessment = results.get('combined_assessment', 0)
107
  if isinstance(combined_assessment, str) and combined_assessment.lower() == "deepfake":
108
  analysis_result = "a deepfake"
109
  else:
110
  combined_assessment = int(combined_assessment) if str(combined_assessment).isdigit() else 0
111
  analysis_result = "genuine/original" if combined_assessment < 50 else "a deepfake"
112
+
113
  output = {
114
  "message": f"According to our analysis, the video you uploaded appears to be {analysis_result}. "
115
  f"{len(results['video_analysis']['frame_results'])} frames were analyzed in total."
 
120
  logging.error(f"Error during analysis: {e}")
121
  return {"error": "An error occurred during video analysis. Please check your input and try again."}
122
 
123
+ # Interface with CAPTCHA verification
124
+ def main_interface():
125
+ with gr.Blocks() as interface:
126
+ gr.Markdown("# AllMark - Deepfake Analyzer")
127
+ gr.Markdown("Please solve the CAPTCHA to proceed with video analysis.")
128
+
129
+ # Display CAPTCHA and input box for user response
130
+ captcha_text = gr.Textbox(label="CAPTCHA", value=captcha_solution, interactive=False)
131
+ captcha_input = gr.Textbox(label="Enter CAPTCHA Here")
132
+ captcha_output = gr.Textbox(label="CAPTCHA Status", interactive=False)
133
+
134
+ # Verify CAPTCHA button
135
+ verify_button = gr.Button("Verify CAPTCHA")
136
+
137
+ # Video analysis components (hidden initially)
138
+ with gr.Column(visible=False) as analysis_components:
139
+ video_input = gr.Video(label="Upload Video")
140
+ analysis_output = gr.JSON(label="Analysis Result")
141
+
142
+ # Submit button for video analysis
143
+ analyze_button = gr.Button("Analyze Video")
144
+ analyze_button.click(analyze_video, inputs=video_input, outputs=analysis_output)
145
+
146
+ # Handle CAPTCHA verification
147
+ def verify_captcha_click(input_text):
148
+ message, success, new_captcha = verify_captcha(input_text)
149
+ if success:
150
+ analysis_components.visible = True
151
+ return message, new_captcha
152
+
153
+ # Update both CAPTCHA message and CAPTCHA text dynamically
154
+ verify_button.click(verify_captcha_click, inputs=captcha_input, outputs=[captcha_output, captcha_text])
155
 
156
+ return interface
 
 
 
 
 
 
157
 
158
+ # Launch interface
159
  if __name__ == "__main__":
160
+ main_interface().launch()