Spaces:
Sleeping
Sleeping
File size: 10,250 Bytes
12324e4 aa4ba7c 12324e4 aa4ba7c 7a15384 aa4ba7c 7a15384 12324e4 aa4ba7c 7a15384 c189f5c 12324e4 |
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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 |
"""
Deepfake Detection System - Gradio Application
"""
import gradio as gr
import os
from pathlib import Path
from utils.detect import DeepfakeDetector
import tempfile
def analyze_media(api_key, media_file, media_type):
"""
Analyze media file for deepfake content
Args:
api_key: Gemini API key
media_file: Uploaded file
media_type: "Image" or "Video"
Returns:
tuple: (result_html, confidence_score, verdict)
"""
# Validate API key
if not api_key or api_key.strip() == "":
return (
"β οΈ **Error**: Please enter your Gemini API key first.",
None,
None
)
# Validate file upload
if media_file is None:
return (
"β οΈ **Error**: Please upload a file to analyze.",
None,
None
)
try:
# Get file path
file_path = media_file.name if hasattr(media_file, 'name') else media_file
# Initialize detector
detector = DeepfakeDetector(api_key.strip())
# Perform analysis based on media type
if media_type == "Image":
results = detector.analyze_image(file_path)
else: # Video
results = detector.analyze_video(file_path, max_frames=10)
# Check for errors
if 'error' in results:
return (
f"β **Error during analysis**: {results['error']}\n\nPlease check your API key and try again.",
None,
None
)
# Format results
result_html = format_results(results, media_type)
confidence = results.get('confidence_score', 0)
verdict = "π΄ LIKELY DEEPFAKE" if results.get('is_deepfake', False) else "π’ LIKELY AUTHENTIC"
return result_html, confidence, verdict
except Exception as e:
return (
f"β **Error**: {str(e)}\n\nPlease check your file and API key, then try again.",
None,
None
)
def format_results(results, media_type):
"""Format analysis results as HTML"""
is_fake = results.get('is_deepfake', False)
confidence = results.get('confidence_score', 0)
analysis = results.get('analysis', 'No analysis available.')
indicators = results.get('indicators', [])
# Build HTML output
#html = f"""
#<div style="font-family: Arial, sans-serif;">
# <h2>π Analysis Results</h2>"""
# First, define the conditional style string
style = (
"background-color: #fee; border-left: 4px solid #f00;"
if is_fake else
"background-color: #efe; border-left: 4px solid #0f0;"
)
# Then build the full HTML block using that style
html = f"""
<div style="font-family: Arial, sans-serif;">
<h2>π Analysis Results</h2>
<div style="{style} padding: 15px; margin: 10px 0;">
<h3>{'π΄ LIKELY DEEPFAKE/AI-GENERATED' if is_fake else 'π’ LIKELY AUTHENTIC'}</h3>
</div>
"""
html = f"""
<div style="background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px;">
<h3>π Detection Metrics</h3>
<p><strong>Confidence Score:</strong> {confidence:.1f}%</p>
<p><strong>Authenticity:</strong> {100 - confidence:.1f}%</p>
<p><strong>Risk Level:</strong> {'High' if confidence > 70 else 'Medium' if confidence > 40 else 'Low'}</p>
</div>
<div style="background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px;">
<h3>π Detailed Analysis</h3>
<p style="white-space: pre-wrap;">{analysis}</p>
</div>
"""
# Add indicators if found
if indicators:
html += """
<div style="background: #fff3cd; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #ffc107;">
<h3>β οΈ Deepfake Indicators Detected</h3>
<ul>
"""
for indicator in indicators[:5]:
html += f"<li>{indicator}</li>"
html += """
</ul>
</div>
"""
# Add video-specific results
if media_type == "Video" and 'frame_analysis' in results:
frame_data = results['frame_analysis']
html += f"""
<div style="background: #e7f3ff; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #2196F3;">
<h3>π¬ Frame-by-Frame Analysis</h3>
<p><strong>Total Frames Analyzed:</strong> {frame_data.get('total_frames', 0)}</p>
<p><strong>Suspicious Frames:</strong> {frame_data.get('suspicious_frames', 0)}</p>
</div>
"""
# Add recommendations
html += """
<div style="background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px;">
<h3>π‘ Recommendations</h3>
"""
if is_fake:
html += """
<p><strong>This media shows signs of manipulation or AI generation. Consider:</strong></p>
<ul>
<li>Verifying the source</li>
<li>Looking for corroborating evidence</li>
<li>Checking metadata</li>
<li>Consulting additional verification tools</li>
<li>Being cautious about sharing</li>
</ul>
"""
else:
html += """
<p><strong>This media appears authentic, but remember:</strong></p>
<ul>
<li>No detection system is 100% accurate</li>
<li>Always verify important content through multiple sources</li>
<li>Check the original source when possible</li>
</ul>
"""
html += """
</div>
</div>
"""
return html
# Create Gradio interface
def create_interface():
"""Create and configure Gradio interface"""
with gr.Blocks(title="Deepfake Detection System", theme=gr.themes.Soft()) as demo:
# Header
gr.Markdown("""
# π Deepfake Detection System
### Analyze images and videos for AI-generated or manipulated content
This system uses Google's Gemini AI to detect deepfakes and AI-generated content in media files.
""")
# API Key Section
with gr.Row():
with gr.Column(scale=3):
api_key_input = gr.Textbox(
label="π Gemini API Key",
type="password",
placeholder="Enter your Google Gemini API key here...",
info="Get your free API key from https://makersuite.google.com/app/apikey"
)
with gr.Column(scale=1):
gr.Markdown("""
### π How to get API Key:
1. Visit [Google AI Studio](https://makersuite.google.com/app/apikey)
2. Sign in with Google
3. Create API key
4. Paste it here
""")
gr.Markdown("---")
# Main Interface
with gr.Row():
with gr.Column(scale=1):
# Media Type Selection
media_type = gr.Radio(
choices=["Image", "Video"],
value="Image",
label="π Select Media Type",
info="Choose the type of media you want to analyze"
)
# File Upload
media_file = gr.File(
label="π€ Upload Media File",
file_types=["image", "video"],
type="filepath"
)
# Analyze Button
analyze_btn = gr.Button(
"π Analyze Media",
variant="primary",
size="lg"
)
# Quick Stats
gr.Markdown("""
### π Supported Formats
**Images:** JPG, PNG, WEBP
**Videos:** MP4, AVI, MOV, MKV
### β±οΈ Processing Time
**Images:** 5-15 seconds
**Videos:** 30-60 seconds
""")
with gr.Column(scale=2):
# Results Display
gr.Markdown("### π Analysis Results")
with gr.Row():
verdict_output = gr.Textbox(
label="Verdict",
interactive=False,
scale=2
)
confidence_output = gr.Number(
label="Confidence Score (%)",
interactive=False,
scale=1
)
result_output = gr.HTML(
label="Detailed Analysis"
)
# Footer
gr.Markdown("""
---
### β οΈ Important Notes
- **Not 100% Accurate**: No detection system is perfect. Always verify through multiple sources.
- **Privacy**: Your API key and files are not stored. They're only used for analysis.
- **For Educational Use**: This tool is for educational and research purposes.
### π οΈ Technology Stack
Built with: Google Gemini AI β’ Gradio β’ OpenCV β’ Python
""")
# Connect the analyze button
analyze_btn.click(
fn=analyze_media,
inputs=[api_key_input, media_file, media_type],
outputs=[result_output, confidence_output, verdict_output]
)
# Examples section
gr.Markdown("""
### π‘ Tips for Best Results
- Use high-quality images and videos
- Ensure good lighting in the media
- Videos should be at least 5 seconds long
- Check multiple suspicious areas if available
""")
return demo
# Launch the application
if __name__ == "__main__":
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
) |