hashirlodhi commited on
Commit
4d27d80
Β·
verified Β·
1 Parent(s): 6d3aa58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -74
app.py CHANGED
@@ -1,106 +1,114 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- import os
4
 
5
- # Global variable to store the pipeline
6
- deepfake_pipe = None
 
 
 
 
 
 
7
 
8
- def load_model():
9
- """Load the model once and cache it"""
10
- global deepfake_pipe
11
- if deepfake_pipe is None:
12
- print("Loading Deepfake Detection Model...")
13
- deepfake_pipe = pipeline(
14
- "image-classification",
15
- model="prithivMLmods/Deep-Fake-Detector-v2-Model"
16
- )
17
- print("Model loaded successfully!")
18
- return deepfake_pipe
19
-
20
- def predict_deepfake(image):
21
- """Predict if image is deepfake or real"""
22
- try:
23
- # Load model if not already loaded
24
- pipe = load_model()
25
-
26
- # Make prediction
27
- results = pipe(image)
28
-
29
- # Format results
30
- prediction = {result['label']: result['score'] for result in results}
31
-
32
- # Determine final verdict
33
- deepfake_score = prediction.get('Deepfake', 0)
34
- realism_score = prediction.get('Realism', 0)
35
-
36
- if deepfake_score > realism_score:
37
- verdict = f"🚨 DEEPFAKE DETECTED ({deepfake_score:.2%} confidence)"
38
- color = "red"
39
- else:
40
- verdict = f"βœ… REAL IMAGE ({realism_score:.2%} confidence)"
41
- color = "green"
42
 
43
- return prediction, verdict
 
 
44
 
45
- except Exception as e:
46
- return {"Error": 1.0}, f"❌ Prediction failed: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # Create the Gradio interface
49
- with gr.Blocks(theme=gr.themes.Soft(), title="Jerry - Deepfake Detector") as demo:
50
  gr.Markdown(
51
  """
52
- # πŸ•΅οΈ Jerry - Deepfake Detection Tool
53
- **Upload an image to check if it's real or AI-generated!**
54
 
 
55
  """
56
  )
57
 
58
  with gr.Row():
59
- with gr.Column():
60
  image_input = gr.Image(
61
- type="filepath",
62
- label="Upload Image",
63
- height=300
64
  )
65
- analyze_btn = gr.Button("πŸ” Analyze Image", variant="primary")
66
-
67
- with gr.Column():
68
- results_output = gr.Label(
69
- label="Detection Results",
70
- num_top_classes=2
71
  )
72
- verdict_output = gr.Textbox(
73
- label="Verdict",
74
- interactive=False
 
 
75
  )
76
 
77
- # Set up the analysis function
78
- analyze_btn.click(
79
- fn=predict_deepfake,
80
- inputs=image_input,
81
- outputs=[results_output, verdict_output]
82
- )
83
-
84
  gr.Markdown(
85
  """
86
  ---
87
- **How it works:**
88
- - Upload any facial image
89
- - Jerry analyzes it and give appropriate verdict
90
- - Returns confidence scores for "Deepfake" vs "Realism"
91
 
92
- **Note:** The model loads only once when first used, then runs quickly for subsequent predictions!
 
93
  """
94
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  # Launch the app
97
  if __name__ == "__main__":
98
- print("πŸš€ Starting Jerry - Deepfake Detection App...")
99
- print("Model will load on first prediction...")
100
-
101
  demo.launch(
102
- share=False,
103
- server_name="127.0.0.1", # Changed from 0.0.0.0 to localhost
104
  server_port=7860,
105
- show_error=True
106
  )
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ import torch
4
 
5
+ # Initialize the deepfake detection pipeline
6
+ print("Loading Jerry's detection system...")
7
+ pipe = pipeline(
8
+ "image-classification",
9
+ model="prithivMLmods/Deep-Fake-Detector-v2-Model",
10
+ device=0 if torch.cuda.is_available() else -1
11
+ )
12
+ print("Jerry is ready!")
13
 
14
+ def detect_deepfake(image):
15
+ """
16
+ Analyze an image to detect if it's a deepfake
17
+ """
18
+ if image is None:
19
+ return "Please upload an image first!"
20
+
21
+ # Get predictions from the model
22
+ results = pipe(image)
23
+
24
+ # Format the results
25
+ output_text = "πŸ” **Jerry's Analysis Results:**\n\n"
26
+
27
+ for result in results:
28
+ label = result['label']
29
+ confidence = result['score'] * 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Create a visual confidence bar
32
+ bar_length = int(confidence / 5)
33
+ bar = "β–ˆ" * bar_length + "β–‘" * (20 - bar_length)
34
 
35
+ output_text += f"**{label}**: {confidence:.2f}%\n"
36
+ output_text += f"{bar}\n\n"
37
+
38
+ # Add a conclusion
39
+ top_result = results[0]
40
+ if top_result['score'] > 0.7:
41
+ certainty = "high"
42
+ elif top_result['score'] > 0.5:
43
+ certainty = "moderate"
44
+ else:
45
+ certainty = "low"
46
+
47
+ output_text += f"\n🎯 **Jerry's Verdict:** {top_result['label']} (with {certainty} confidence)"
48
+
49
+ return output_text
50
 
51
  # Create the Gradio interface
52
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
53
  gr.Markdown(
54
  """
55
+ # πŸ•΅οΈ Jerry - Deepfake Detector
56
+ ### Your AI-Powered Image Authenticity Analyzer
57
 
58
+ Upload an image and let Jerry analyze it to determine if it's authentic or artificially generated!
59
  """
60
  )
61
 
62
  with gr.Row():
63
+ with gr.Column(scale=1):
64
  image_input = gr.Image(
65
+ label="Upload Image for Analysis",
66
+ type="pil",
67
+ height=400
68
  )
69
+ analyze_btn = gr.Button(
70
+ "πŸ” Analyze with Jerry",
71
+ variant="primary",
72
+ size="lg"
 
 
73
  )
74
+
75
+ with gr.Column(scale=1):
76
+ output_text = gr.Markdown(
77
+ label="Detection Results",
78
+ value="Upload an image and click 'Analyze with Jerry' to begin!"
79
  )
80
 
 
 
 
 
 
 
 
81
  gr.Markdown(
82
  """
83
  ---
84
+ ### πŸ’‘ Tips for Best Results:
85
+ - Upload clear, high-quality images
86
+ - Works best with photos of faces or people
87
+ - Supports common image formats (JPG, PNG, etc.)
88
 
89
+ ### ⚠️ Important Note:
90
+ Jerry provides analysis based on AI detection patterns. Results should be used as guidance, not absolute proof.
91
  """
92
  )
93
+
94
+ # Connect the button to the function
95
+ analyze_btn.click(
96
+ fn=detect_deepfake,
97
+ inputs=image_input,
98
+ outputs=output_text
99
+ )
100
+
101
+ # Also allow Enter key or automatic analysis
102
+ image_input.change(
103
+ fn=detect_deepfake,
104
+ inputs=image_input,
105
+ outputs=output_text
106
+ )
107
 
108
  # Launch the app
109
  if __name__ == "__main__":
 
 
 
110
  demo.launch(
111
+ server_name="0.0.0.0",
 
112
  server_port=7860,
113
+ share=False
114
  )