Spaces:
Sleeping
Sleeping
File size: 4,935 Bytes
9c4b1c4 a721e26 9c4b1c4 a721e26 9c4b1c4 ee73b8f 9c4b1c4 ee73b8f 9c4b1c4 ee73b8f 9c4b1c4 ee73b8f 9c4b1c4 ee73b8f 9c4b1c4 ee73b8f 9c4b1c4 b3a3661 9c4b1c4 ee73b8f 9c4b1c4 ee73b8f 9c4b1c4 b8c4518 |
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 |
import gradio as gr
import os
import sys
import json
import argparse
from types import SimpleNamespace
# Try to import detector - if this fails, we'll show an error in the UI
try:
from support.detect import run_detect
DETECTOR_AVAILABLE = True
IMPORT_ERROR = None
except Exception as e:
DETECTOR_AVAILABLE = False
IMPORT_ERROR = str(e)
print(f"Warning: Could not import detector: {e}")
# Create a dummy function
def run_detect(args):
raise ImportError(f"Detector not available: {IMPORT_ERROR}")
# Download weights on first run (for HF Spaces)
if os.environ.get("SPACE_ID"):
try:
from download_weights import download_all_weights
download_all_weights()
except Exception as e:
print(f"Warning: Could not download weights: {e}")
# Available detectors based on launcher.py
DETECTORS = ['R50_TF', 'R50_nodown', 'CLIP-D', 'P2G', 'NPR']
def predict(image_path, detector_name):
# Check if detector is available
if not DETECTOR_AVAILABLE:
return json.dumps({
"error": "Detector module not available",
"details": IMPORT_ERROR,
"message": "The detection system could not be initialized. Please check the logs."
}, indent=2)
if not image_path:
return json.dumps({"error": "Please upload an image."}, indent=2)
# Create a temporary output file path
output_path = "temp_result.json"
# Mock args object
args = SimpleNamespace(
image=image_path,
detector=detector_name,
config_dir='configs',
output=output_path,
weights='pretrained', # Use default/pretrained
device='cpu', # Force CPU
dry_run=False,
verbose=False
)
try:
# Run detection
# We need to capture stdout/stderr or just trust the function
# run_detect might raise FileNotFoundError if weights are missing
run_detect(args)
# Read results
if os.path.exists(output_path):
with open(output_path, 'r') as f:
result = json.load(f)
# Format output
prediction = result.get('prediction', 'Unknown')
confidence = result.get('confidence', 0.0)
elapsed_time = result.get('elapsed_time', 0.0)
output = {
"Prediction": prediction,
"Confidence": f"{confidence:.4f}",
"Elapsed Time": f"{elapsed_time:.3f}s"
}
return json.dumps(output, indent=2)
else:
return json.dumps({"error": "No result file generated. Check console logs for details."}, indent=2)
except FileNotFoundError as e:
return json.dumps({
"error": str(e),
"message": f"Please ensure you have downloaded the weights for {detector_name}."
}, indent=2)
except Exception as e:
return json.dumps({"error": str(e)}, indent=2)
finally:
# Cleanup
if os.path.exists(output_path):
os.remove(output_path)
# Create Gradio Interface
# Use theme only if gradio version supports it
try:
demo = gr.Blocks(title="Deepfake Detection", theme=gr.themes.Soft())
except TypeError:
# Older gradio version doesn't support theme parameter
demo = gr.Blocks(title="Deepfake Detection")
with demo:
gr.Markdown("# π Deepfake Detection Library")
gr.Markdown("""
Upload an image and select a detector to check if it's real or fake.
**Available Detectors:**
- **R50_TF**: ResNet-50 based detector
- **R50_nodown**: ResNet-50 without downsampling
- **CLIP-D**: CLIP-based detector
- **P2G**: Prompt2Guard detector
- **NPR**: Neural Posterior Regularization
""")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="filepath", label="Input Image", height=400)
detector_input = gr.Dropdown(
choices=DETECTORS,
value=DETECTORS[0],
label="Select Detector",
info="Choose which deepfake detection model to use"
)
submit_btn = gr.Button("π Detect", variant="primary")
with gr.Column():
output_display = gr.Code(label="Detection Results", language="json", lines=10)
gr.Markdown("""
---
### About
This Space provides access to multiple state-of-the-art deepfake detection models.
All models are trained on StyleGAN2, StableDiffusionXL, FFHQ, and FORLAB datasets.
**Note:** First detection may be slower due to model loading.
""")
submit_btn.click(
fn=predict,
inputs=[image_input, detector_input],
outputs=output_display
)
if __name__ == "__main__":
# For HF Spaces, configure server settings
demo.launch(server_name="0.0.0.0", server_port=7860)
|