""" 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""" #
#

📊 Analysis Results

""" # 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"""

📊 Analysis Results

{'🔴 LIKELY DEEPFAKE/AI-GENERATED' if is_fake else '🟢 LIKELY AUTHENTIC'}

""" html = f"""

📈 Detection Metrics

Confidence Score: {confidence:.1f}%

Authenticity: {100 - confidence:.1f}%

Risk Level: {'High' if confidence > 70 else 'Medium' if confidence > 40 else 'Low'}

🔍 Detailed Analysis

{analysis}

""" # Add indicators if found if indicators: html += """

⚠️ Deepfake Indicators Detected

    """ for indicator in indicators[:5]: html += f"
  • {indicator}
  • " html += """
""" # Add video-specific results if media_type == "Video" and 'frame_analysis' in results: frame_data = results['frame_analysis'] html += f"""

🎬 Frame-by-Frame Analysis

Total Frames Analyzed: {frame_data.get('total_frames', 0)}

Suspicious Frames: {frame_data.get('suspicious_frames', 0)}

""" # Add recommendations html += """

💡 Recommendations

""" if is_fake: html += """

This media shows signs of manipulation or AI generation. Consider:

  • Verifying the source
  • Looking for corroborating evidence
  • Checking metadata
  • Consulting additional verification tools
  • Being cautious about sharing
""" else: html += """

This media appears authentic, but remember:

  • No detection system is 100% accurate
  • Always verify important content through multiple sources
  • Check the original source when possible
""" html += """
""" 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 )