(major)feat: add new functionalities for AI-generated content detection
Browse files- Introduced a comprehensive project introduction and implementation strategy for AI-generated content detection.
- Added new Gradio tabs for wavelet blocking noise estimation, bit plane extraction, and EXIF metadata extraction.
- Enhanced the user interface to include detailed descriptions for each new feature, improving usability and accessibility.
Files changed (4)
- app_mcp.py+87
- utils/bitplane.pyAdded+27
- utils/exif.pyAdded+11
- utils/wavelet.pyAdded+20
16 unmodified lines17181920212264 unmodified lines878889909192248 unmodified lines34134234334434534634734834935035135216 unmodified linesfrom utils.minmax import preprocess as minmax_preprocessfrom utils.ela import genELA as ELAfrom forensics.registry import register_model, MODEL_REGISTRY, ModelEntry# Configure logging64 unmodified lines}def preprocess_resize_256(image):if image.mode != 'RGB':image = image.convert('RGB')248 unmodified lines],outputs=outputs)with gr.Tab("👑 Community Forensics Preview"):temp_space = gr.load("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview", src="spaces")# preview # no idea if this will workwith gr.Tab("🥇 Leaderboard"):gr.Markdown("# AI Generated / Deepfake Detection Models Leaderboard: Soon™")# Launch the interfacedemo.launch(share=True)16 unmodified lines1718192021222324252627282964 unmodified lines949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150248 unmodified lines39940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843916 unmodified linesfrom utils.minmax import preprocess as minmax_preprocessfrom utils.ela import genELA as ELAfrom forensics.registry import register_model, MODEL_REGISTRY, ModelEntryimport pywtimport cv2import tempfileimport exiftoolfrom utils.wavelet import wavelet_blocking_noise_estimationfrom utils.bitplane import bit_plane_extractorfrom utils.exif import exif_full_dump# Configure logging64 unmodified lines}QUICK_INTRO = """### AI-Generated Content Detection: The Tipping PointRemember that high-stakes game of whack-a-mole between deepfakes and detection algorithms that the world leaders promised to fund and fight? Well, to no surprise, that battle ended with what seems like a quiet acceptance of defeat. Despite massive increases in 2024 for research and funding for detection systems, it came to no surprise to anyone when the largest public detection project to date was effectively rendered useless just weeks after release.Then came the sucker-punches. Month after month, SOTA models started dropping like they were on a release calendar:• Hyper-realistic voice clones reading your emotional tells• Zero-shot everything making reality checks irrelevant• Image models that upgraded "plausible" to "indistinguishable" overnightIt was terrifying. Exhilarating. Hands-down the most fascinating existential rollercoaster since crypto crashed. And we all know why detection lost: **Defense always lags offense.** Pouring billions into bigger, slower models was like building thicker castle walls while the enemy developed drone strikes.The research exodus wasn't betrayal – it was sanity. Why battle an unwinnable arms race when there's actual progress to be made elsewhere? And let's be honest: we saw this coming. When has humanity ever resisted accelerating technology that promises... *interesting* applications? As the ancients wisely tweeted: 🔞 drives innovation.So what now? We pivot.✅ Stop pretending we'll ever "solve" deepfakes. Accept they'll keep evolving.✅ Learn from cybersecurity: Shift from impossible prevention to damage control✅ Embrace and strive for radical efficiency – 10X the output at 0.1X the resource burnBut here's the silver lining, the hard-won wisdom, and the next chapter: efficiency. It's time to shift our focus from perpetual catch-up to smarter integration and acceptance.Because our current approach? Training mammoth models on volcanic-scale energy consumption to chase diminishing returns? That's the real deepfake we should be fighting.Next section: Practical, absurdly efficient alternatives already showing promise. It's not SOTA, but it just makes sense. ⚡"""IMPLEMENTATION = """### 1. **Shift away from the belief that more data leads to better results. Rather, focus on insight-driven and "quality over quantity" datasets in training.*** **Move Away from Terabyte-Scale Datasets**: Focus on **quality over quantity** by curating a smaller, highly diverse, and **labeled dataset** emphasizing edge cases and the latest AI generations.* **Active Learning**: Implement active learning techniques to iteratively select the most informative samples for human labeling, reducing dataset size while maintaining effectiveness.### 2. **Efficient Model Architectures*** **Adopt Lightweight, State-of-the-Art Models**: Explore models designed for efficiency like MobileNet, EfficientNet, or recent advancements in vision transformers (ViTs) tailored for forensic analysis.* **Transfer Learning with Fine-Tuning**: Leverage pre-trained models fine-tuned on your curated dataset to leverage general knowledge while adapting to specific AI image detection tasks.### 3. **Multi-Modal and Hybrid Approaches*** **Combine Image Forensics with Metadata Analysis**: Integrate insights from image processing with metadata (e.g., EXIF, XMP) for a more robust detection framework.* **Incorporate Knowledge Graphs for AI Model Identification**: If feasible, build or utilize knowledge graphs mapping known AI models to their generation signatures for targeted detection.### 4. **Continuous Learning and Update Mechanism*** **Online Learning or Incremental Training**: Implement a system that can incrementally update the model with new, strategically selected samples, adapting to new AI generation techniques.* **Community-Driven Updates**: Establish a feedback loop with users/community to report undetected AI images, fueling model updates.### 5. **Evaluation and Validation*** **Robust Validation Protocols**: Regularly test against unseen, diverse datasets including novel AI generations not present during training.* **Benchmark Against State-of-the-Art**: Periodically compare performance with newly published detection models or techniques."""def preprocess_resize_256(image):if image.mode != 'RGB':image = image.convert('RGB')248 unmodified lines],outputs=outputs)with gr.Tab("🙈 Project Introduction"):gr.Markdown("# AI Generated / Deepfake Detection Models Leaderboard: Soon™")with gr.Tab("👑 Community Forensics Preview"):temp_space = gr.load("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview", src="spaces")# preview # no idea if this will workwith gr.Tab("🥇 Leaderboard"):gr.Markdown("# AI Generated / Deepfake Detection Models Leaderboard: Soon™")with gr.Tab("Wavelet Blocking Noise Estimation"):gr.Interface(fn=wavelet_blocking_noise_estimation,inputs=[gr.Image(type="pil"), gr.Slider(1, 32, value=8, step=1, label="Block Size")],outputs=gr.Image(type="pil"),description="Wavelet-based local noise estimation")with gr.Tab("Bit Plane Values"):gr.Interface(fn=bit_plane_extractor,inputs=[gr.Image(type="pil"),gr.Dropdown(["Luminance", "Red", "Green", "Blue", "RGB Norm"], label="Channel", value="Luminance"),gr.Slider(0, 7, value=0, step=1, label="Bit Plane"),gr.Dropdown(["Disabled", "Median", "Gaussian"], label="Filter", value="Disabled")],outputs=gr.Image(type="pil"),description="Extract and visualize bit planes from different channels.")with gr.Tab("EXIF Full Dump"):gr.Interface(fn=exif_full_dump,inputs=gr.Image(type="pil"),outputs=gr.JSON(),description="Extract all EXIF metadata from the uploaded image.")# Launch the interfacedemo.launch(share=True)
123456789101112131415161718192021222324252627import cv2 as cvimport numpy as npfrom PIL import Image
def bit_plane_extractor( image: Image.Image, channel: str = "Luminance", bit: int = 0, filter_type: str = "Disabled") -> Image.Image: """Extract and visualize a bit plane from a selected channel of the image.""" img = np.array(image.convert("RGB")) if channel == "Luminance": img = cv.cvtColor(img, cv.COLOR_RGB2GRAY) elif channel == "RGB Norm": b, g, r = cv.split(img.astype(np.float64)) img = np.sqrt(np.power(b, 2) + np.power(g, 2) + np.power(r, 2)).astype(np.uint8) else: idx = {"Red": 0, "Green": 1, "Blue": 2}[channel] img = img[:, :, idx] plane = cv.bitwise_and(np.full_like(img, 2 ** bit), img) plane = cv.normalize(plane, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) if filter_type == "Median": plane = cv.medianBlur(plane, 3) elif filter_type == "Gaussian": plane = cv.GaussianBlur(plane, (3, 3), 0) return Image.fromarray(plane) 1234567891011import tempfileimport exiftoolfrom PIL import Image
def exif_full_dump(image: Image.Image) -> dict: """Extract all EXIF metadata from an image using exiftool.""" with tempfile.NamedTemporaryFile(suffix='.jpg', delete=True) as tmp: image.save(tmp.name) with exiftool.ExifTool() as et: metadata = et.get_metadata(tmp.name) return metadata 1234567891011121314151617181920import numpy as npimport pywtimport cv2from PIL import Image
def wavelet_blocking_noise_estimation(image: Image.Image, blocksize: int = 8) -> Image.Image: """Estimate local noise using wavelet blocking. Returns a PIL image of the noise map.""" im = np.array(image.convert('L')) y = np.double(im) cA1, (cH, cV, cD) = pywt.dwt2(y, 'db8') cD = cD[:cD.shape[0] // blocksize * blocksize, :cD.shape[1] // blocksize * blocksize] block = np.zeros((cD.shape[0] // blocksize, cD.shape[1] // blocksize, blocksize ** 2)) for ii in range(0, cD.shape[0] - blocksize + 1, blocksize): for jj in range(0, cD.shape[1] - blocksize + 1, blocksize): block_elements = cD[ii:ii+blocksize, jj:jj+blocksize] block[ii // blocksize, jj // blocksize, :] = block_elements.flatten() noise_map = np.median(np.abs(block), axis=2) / 0.6745 noise_map_8u = cv2.normalize(noise_map, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U) resized_noise_map = cv2.resize(noise_map_8u, (im.shape[1], im.shape[0]), interpolation=cv2.INTER_NEAREST) return Image.fromarray(resized_noise_map) app_mcp.py+87
utils/bitplane.pyAdded+27
utils/exif.pyAdded+11
utils/wavelet.pyAdded+20