# Project export: AI Deepfake Detector Extension

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2025
- Tagline: Real Time Deepfake Detection that removes fake generated posts live while browsing, removing potential propaganda and misinformation.
- Devpost: https://devpost.com/software/ai-deepfake-detector-extension
- GitHub: https://github.com/ohsmaan/ai-deepfake-detection.git
- Team: 1 GitHub contributor(s) — Osman Adel (14 commits)

## Devpost submission (written by the team)

### Inspiration

My mother sent me a post that was AI generated, she fully believed it and it was difficult to convince her of the truth, AI has gotten so intelligent that it is fooling the older and non technical folks of our society at an unprecedented level. Furthermore, there are nefarious webpages dedicated to deepfakes of real women in explicit poses, without their consent.

### What it does

This is a google extension that allows a person to manually detect if an image, video, audio, or text is AI generated. The magnum opus is that it is able to run in real time and remove altered and nefarious AI posts from your YouTube, Twitter (X), Instagram, Tiktok etc. feeds, removing the worry that something is altered and protecting people like my mother who could also get potentially misinformed, scammed, or worse.

### How we built it

We (I) built it using multiple LLM's for guidance and ran huggingface models locally that have 100+M parameters alongside LLM's (Llama via Groq) dedicated to detecting deepfake faces, deepfake audio, deepfake texts, and deepfake videos. We used fastapi as our backend along with Javascript and google web extensions to build the extension.

### Challenges we ran into

It was very difficult to find and optimize a model so that real time detection does not take minutes to clear a feed, along with removing youtube posts, twitter posts, instagram comments, etc. It was also difficult to get fast llm readings (until groq!). Furthermore, using a CPU only build without CUDA made processing difficult.

### Accomplishments we're proud of

We are proud that we were able to accomplish real time detection and were able to scan and remove posts quickly for the user.

### What we learned

Learned a lot about deepfakes, a lot of huggingface and their models, along with trying Groq for the first time. This was also the first time making an extension.

### What's next

Next up is optimizing and going beyond an extension to hopefully detect explicit material of unconsented individuals and reporting it to authorities, we also want to improve on detection and confidence with finetuning (veo 3 is difficult to detect.) Along with utilizing our detection technology to prevent scammers and impersonators. But before all of that we need to deploy a server. We also want to improve our UI as it is very barebones and basically auto generated, we spent a lot of our time on the backend.

## README (from the GitHub repository)

# ai-deepfake-detection
UC Berkeley AI Hackathon Project - AI Deepfake Detection that allows users to detect if something is fake/made with AI.


## Detected evidence (automated analysis)

Indexed codebase: 44 recognized source files, 259 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- Hugging Face (technology) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- PyTorch (technology) — detected in the code

## Codebase structure (from repository index)

### Files (50 of 50)

```
.gitignore
backend/app.py
backend/services/__init__.py
backend/services/aggregation_service.py
backend/services/ai_service.py
backend/services/claude_service.py
backend/services/file_service.py
backend/services/hf_api_service.py
backend/services/local_video_service.py
backend/services/text_service.py
backend/services/video_service.py
backend/test_text.py
debug_model.py
debug_system.py
demo/demo_content/README.md
demo/demo_script.md
extension/background.js
extension/background/api-client.js
extension/background/storage.js
extension/content.css
extension/content.js
extension/content/content-blocking.js
extension/content/video-detection.js
extension/manifest.json
extension/popup.css
extension/popup.html
extension/popup.js
extension/README.md
extension/utils/dom-utils.js
extension/utils/file-utils.js
extension/welcome.html
INSTALLATION_GUIDE.md
LICENSE
poetry.lock
pyproject.toml
README.md
scripts/predownload_model.py
shell.nix
simple_api_test.py
test_detection.py
test_extension.py
test_hf_model.py
test_video_detection.py
test_wav2vec2.py
tests/test_api/test_text_endpoint.py
tests/test_api/test_video_endpoint.py
tests/test_services/test_aggregation_service.py
tests/test_services/test_local_video_service.py
tests/test_text_utils.py
tests/test_video_utils.py
```

### Dependencies

- pyproject.toml: aiofiles@^23.2.1, anthropic@^0.54.0, black@^23.3.0, fastapi@^0.115.13, flake8@^6.0.0, groq@^0.28.0, huggingface-hub@^0.33.0, mypy@^1.2.0, numpy@^2.3.1, opencv-python@4.11.0.86, pillow@^11.2.1, pydub@^0.25.1, pytest@^7.2.0, python-dotenv@^1.1.0, python-multipart@^0.0.20, requests@^2.32.4, scikit-learn@1.7.0, scipy@^1.14.0, sentence-transformers@4.1.0, soundfile@^0.12.1, torch@^2.7.1, torchaudio@2.7.1, torchvision@^0.22.1, transformers@4.52.4, uvicorn@^0.34.3

### Recent commits (newest first)

- added text detection with groq, dont know if it will fry the pc or make it slow but its good now
- working prototype that removes videos from twitter timeline and dalle and youtube home page if its AI
- working test of blocking videos live; 5:22am
- around 5 second to load image detection,will need to lower (rent gpus?) time: 11:38pm
- added extension capabilities, problems: need to make the detection faster (will test with gpu) GUI is shit and prob more problems, 11:11pm
- the rest of the commit, forgot to go into parent, june 21 6:35pm
- working fastapi that has good detection (has not had a false positive yet; june 21 6:34pm
- added endpoints to fastapi, will need more
- added the boilerplate/beginningfoundations of the project - 3:27pm
- added anthropic to poetry
- adding more things to the backend folder, boilerplate files
- Added more things to poetry (fastapi etc.) Created folders/structure to start the project
- Initial project files: poetry setup, starter code
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### INSTALLATION_GUIDE.md

```markdown
# AI Deepfake Detector - Complete Installation Guide

## 🎯 Project Overview

A complete AI deepfake detection system with:
- **FastAPI Backend**: Hugging Face model integration for image analysis
- **Chrome Extension**: Real-time detection on web pages
- **Claude AI Integration**: Detailed analysis and explanations

## 🚀 Quick Start

### 1. Prerequisites

- Python 3.8+ with Poetry
- Chrome browser
- Internet connection (for model downloads)

### 2. Backend Setup

```bash
# Clone and setup
cd backend
poetry install
poetry run python app.py
```

The backend will run on `http://localhost:8000`

### 3. Chrome Extension Setup

1. Open Chrome and go to `chrome://extensions/`
2. Enable "Developer mode" (toggle in top right)
3. Click "Load unpacked"
4. Select the `extension` folder from this project
5. The extension icon should appear in your toolbar

### 4. Test the System

1. Navigate to any webpage with images (Twitter, Facebook, etc.)
2. Click the extension icon
3. Click "Scan Page Images" to analyze all images
4. Or click on individual image overlays for instant detection

## 📁 Project Structure

```
ai-deepfake-detector/
├── backend/                 # FastAPI backend
│   ├── app.py              # Main API server
│   ├── services/           # AI services
│   └── pyproject.toml      # Dependencies
├── extension/              # Chrome extension
│   ├── manifest.json       # Extension config
│   ├── popup.html/js/css   # Extension UI
│   ├── content.js/css      # Page overlays
│   ├── background.js       # Background processing
│   └── welcome.html        # Welcome page
├── demo/                   # Demo files
├── tests/                  # Test scripts
└── README.md              # This file
```

## 🔧 Configuration

### Environment Variables

Create a `.env` file in the backend directory:

```env
ANTHROPIC_API_KEY=your_claude_api_key_here
```

### Extension Settings

The extension has configurable settings:
- **Auto-scan**: Automatically scan images on page load
- **Show Overlay**: Display clickable overlays on images

## 🧪 Testing

### Backend API Test

```bash
python test_extension.py
```

This tests:
- Health endpoint
- Model info endpoint
- Image upload and detection
- CORS configuration

### Manual Testing

1. **Backend**: Visit `http://localhost:8000/docs` for API documentation
2. **Extension**: Test on social media sites with profile pictures
3. **Integration**: Use the extension popup to scan page images

## 🎯 Demo Scenarios

### Best Test Sites

1. **Twitter/X**: Profile pictures and media posts
2. **Facebook**: Profile photos and shared images
3. **Instagram**: Posts and stories
4. **Reddit**: Image posts and memes
5. **News Sites**: Article images

### Expected Results

- **Real Images**: 60-80% confidence, marked as "Real"
- **AI Generated**: 70-90% confidence, marked as "AI Generated"
- **Processing Time**: 1-3 seconds per image

## 🐛 Troubleshooting

### Backend Issues

1. **Model Loading Error**:
   ```bash
   cd backend
   poetry 
[truncated — 2406 more characters]
```

### pyproject.toml

```
[tool.poetry]
name = "ai-deepfake-detector"
version = "0.1.0"
description = ""
authors = ["ohsmaan"]
readme = ""
package-mode = false

[tool.poetry.dependencies]
python = "^3.12"
# Add your main dependencies here, for example:
torch = "^2.7.1"
torchvision = "^0.22.1"
torchaudio = "2.7.1"
opencv-python = "4.11.0.86"
scikit-learn = "1.7.0"
sentence-transformers = "4.1.0"
transformers = "4.52.4"
uvicorn = "^0.34.3"
python-multipart = "^0.0.20"
anthropic = "^0.54.0"
# Additional dependencies for video processing
aiofiles = "^23.2.1"
numpy = "^2.3.1"
pillow = "^11.2.1"
fastapi = "^0.115.13"
huggingface-hub = "^0.33.0"
python-dotenv = "^1.1.0"
requests = "^2.32.4"
soundfile = "^0.12.1"
scipy = "^1.14.0"
pydub = "^0.25.1"
groq = "^0.28.0"

[tool.poetry.group.dev.dependencies]
black = "^23.3.0"
pytest = "^7.2.0"
mypy = "^1.2.0"
flake8 = "^6.0.0"


```

### backend/app.py

```python
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel
import uvicorn
from typing import Optional, List
import time
import os
import aiofiles
from PIL import Image
import pillow_avif  # Ensure AVIF plugin is loaded
from services.ai_service import AIService
from services.text_service import TextService  # RESTORED - Groq enabled
import io
import uuid
import requests
from transformers.pipelines import pipeline
import cv2
from anthropic import Anthropic
from anthropic.types import TextBlock
from dotenv import load_dotenv
import base64
from transformers import AutoImageProcessor, AutoModelForImageClassification, Wav2Vec2ForSequenceClassification, Wav2Vec2FeatureExtractor

# Initialize AI service with accurate model
ai_service = AIService()
text_service = TextService()  # RESTORED - Groq enabled

# Pydantic models for request/response
class DetectionRequest(BaseModel):
    confidence_threshold: float = 0.5

class DetectionResponse(BaseModel):
    is_deepfake: bool
    confidence: float
    processing_time: float
    message: str
    model_used: str
    claude_analysis: str
    detection_type: str = "unknown"
    analysis: str = ""
    model_note: str = ""

# RESTORED - Groq text detection enabled
class TextDetectionRequest(BaseModel):
    text: str
    confidence_threshold: float = 0.5

class TextDetectionResponse(BaseModel):
    is_bot: bool
    confidence: float
    processing_time: float
    message: str
    model_used: str
    detection_type: str = "human"
    analysis: str = ""
    indicators: List[str] = []
    text_length: int = 0

# FastAPI app configuration
app = FastAPI(
    title="AI Deepfake Detector",
    description="API for detecting deepfake videos and images",
    version="1.0.0"
)

# CORS middleware for frontend integration
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure properly for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Add OPTIONS endpoint for CORS preflight
@app.options("/upload")
async def options_upload():
    """Handle CORS preflight for upload endpoint"""
    return {"message": "OK"}

# Global storage for demo purposes (use database in production)
detection_results = {}
active_requests = set()

@app.get("/")
def root():
    return {"message": "AI Deepfake Detector API is running!"}

@app.get("/health")
def health_check():
    return {"status": "healthy", "timestamp": time.time()}

@app.get("/proxy-image")
async def proxy_image(url: str):
    """Proxy endpoint to fetch images from external URLs, bypassing CORS"""
    try:
        print(f"🔄 Proxying image: {url}")
        
        # Fetch the image from the external URL
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        
        # Get the content type
        content_type = response.headers.get('content-type', 'image/jpeg')
        
        print(f"✅ Image proxied successfully: {len(response.content)} bytes, {content_type}")
        
        # Return the image data
        return Response(
            content=response.content,
            media_type=content_type,
            headers={
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type'
            }
        )
        
    except Exception as e:
        print(f"❌ Proxy error: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to proxy image: {str(e)}")

@app.post("/upload", response_model=DetectionResponse)
async def upload_file(
    file: UploadFile = File(...)
):
    """Upload a video or image file for deepfake detection"""
    
    print(f"📥 Received upload request: {file.filename}, content_type: {file.content_type}, size: {file.size}")
    
    # Validate file type
    allowed_types = ["video/", "image/"]
    if not file.content_type or not any(file.content_type.startswith(t) for t in allowed_types):
        print(f"❌ Invalid file type: {file.content_type}")
        raise HTTPException(
            status_code=400, 
            detail="File must be a video or image"
        )
    
    # Validate file size (50MB limit for demo)
    if file.size and file.size > 50 * 1024 * 1024:
        print(f"❌ File too large: {file.size} bytes")
        raise HTTPException(
            status_code=400, 
            detail="File size must be less than 50MB"
        )
    
    # Generate unique ID for this detection
    detection_id = f"detection_{int(time.time())}_{uuid.uuid4().hex[:8]}"
    
    # Track active requests
    active_requests.add(detection_id)
    print(f"🚀 Starting request {detection_id} (active: {len(active_requests)})")
    
    # Save uploaded file temporarily
    temp_file_path = f"/tmp/{detection_id}_{file.filename}"
    
    print(f"📁 Processing file: {file.filename} ({file.content_type})")
    
    # Save file
    async with aiofiles.open(temp_file_path, 'wb') as f:
        content = await file.read()
        await f.write(content)
    
    print(f"💾 File saved: {temp_file_path} ({len(content)} bytes)")
    
    # Check if file is actually AVIF regardless of content_type or filename
    def is_avif_file(file_path):
        try:
            with open(file_path, 'rb') as f:
                # Check for AVIF signature (first 12 bytes)
                header = f.read(12)
                # AVIF files start with specific bytes
                return header.startswith(b'\x00\x00\x00\x20ftyp') and b'avif' in header
        except:
            return False
    
    # Check if file is actually a GIF
    def is_gif_file(file_path):
        try:
 
[truncated — 28087 more characters]
```

### test_wav2vec2.py

```python
#!/usr/bin/env python3
"""
Test script for wav2vec2 audio deepfake detection
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'backend'))

from services.ai_service import AIService

def test_wav2vec2_loading():
    """Test if the wav2vec2 model loads correctly"""
    print("🧪 Testing wav2vec2 model loading...")
    
    try:
        # Initialize AI service
        ai_service = AIService()
        print("✅ AI service initialized successfully")
        
        # Check model info
        model_info = ai_service.get_model_info()
        print(f"📊 Audio model: {model_info['audio_model']['name']}")
        print(f"📊 Model type: {model_info['audio_model']['model_type']}")
        print(f"📊 Accuracy: {model_info['audio_model']['accuracy']}")
        
        print("✅ Wav2Vec2 model loaded successfully!")
        return True
        
    except Exception as e:
        print(f"❌ Error loading wav2vec2 model: {e}")
        return False

if __name__ == "__main__":
    success = test_wav2vec2_loading()
    sys.exit(0 if success else 1) 
```

### debug_model.py

```python
#!/usr/bin/env python3
from transformers import AutoImageProcessor, AutoModelForImageClassification
from PIL import Image
import torch

def debug_model():
    model_name = "aiwithoutborders-xyz/CommunityForensics-DeepfakeDet-ViT"
    
    print(f"🔍 Debugging model: {model_name}")
    
    try:
        # Load processor and model
        processor = AutoImageProcessor.from_pretrained(model_name)
        model = AutoModelForImageClassification.from_pretrained(model_name)
        
        print(f"✅ Model loaded successfully")
        print(f"📊 Model config: {model.config}")
        print(f"📊 Processor config: {processor.config if hasattr(processor, 'config') else 'No config'}")
        
        # Check what size the processor expects
        if hasattr(processor, 'size'):
            print(f"📏 Processor size: {processor.size}")
        if hasattr(processor, 'crop_size'):
            print(f"📏 Processor crop_size: {processor.crop_size}")
        if hasattr(processor, 'do_resize'):
            print(f"🔄 Processor do_resize: {processor.do_resize}")
        
        # Create a test image
        test_image = Image.new('RGB', (384, 384), color='red')
        print(f"📸 Test image size: {test_image.size}")
        
        # Try processing
        inputs = processor(images=test_image, return_tensors="pt")
        print(f"📦 Input tensor shape: {inputs['pixel_values'].shape}")
        
        # Try inference
        with torch.no_grad():
            outputs = model(**inputs)
            print(f"✅ Inference successful!")
            print(f"📊 Output shape: {outputs.logits.shape}")
            
            # Get prediction
            probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
            confidence, predicted_class = torch.max(probabilities, 1)
            predicted_label = model.config.id2label[predicted_class.item()]
            
            print(f"🎯 Prediction: {predicted_label}")
            print(f"🎯 Confidence: {confidence.item()}")
            
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    debug_model() 
```

### simple_api_test.py

```python
#!/usr/bin/env python3
import os
import requests
from dotenv import load_dotenv

load_dotenv()

def test_api_connectivity():
    print("🔍 Testing API Connectivity (Free Tests)\n")
    
    # Test 1: Check if API keys are loaded
    print("1️⃣ Checking API Keys...")
    anthropic_key = os.getenv("ANTHROPIC_API_KEY")
    hf_token = os.getenv("HUGGINGFACE_TOKEN")
    
    if anthropic_key and anthropic_key != "your_actual_claude_api_key_here":
        print("✅ Anthropic API key found and configured")
    else:
        print("❌ Anthropic API key missing or not set")
    
    if hf_token and hf_token != "your_huggingface_token_here":
        print("✅ Hugging Face token found and configured")
    else:
        print("❌ Hugging Face token missing or not set")
    
    # Test 2: Check Hugging Face model availability (free)
    print("\n2️⃣ Checking Hugging Face Model Availability...")
    if hf_token:
        # Try different deepfake detection models
        models_to_test = [
            "aiwithoutborders-xyz/CommunityForensics-DeepfakeDet-ViT",
            "selimsef/dfdc_deepfake_detection",
            "microsoft/resnet-50"  # Fallback
        ]
        
        for model_id in models_to_test:
            print(f"   Testing {model_id}...")
            url = f"https://api-inference.huggingface.co/models/{model_id}"
            
            headers = {"Authorization": f"Bearer {hf_token}"}
            
            try:
                response = requests.get(url, headers=headers, timeout=10)
                
                if response.status_code == 200:
                    print(f"✅ {model_id} is accessible")
                    model_info = response.json()
                    print(f"📊 Model: {model_info.get('modelId', 'Unknown')}")
                    break  # Use the first available model
                elif response.status_code == 404:
                    print(f"❌ {model_id} not found")
                else:
                    print(f"⚠️  {model_id} returned status {response.status_code}")
                    
            except Exception as e:
                print(f"❌ Error checking {model_id}: {e}")
    else:
        print("⚠️  Skipping HF test - no token")
    
    # Test 3: Check Anthropic API connectivity (free)
    print("\n3️⃣ Checking Anthropic API Connectivity...")
    if anthropic_key:
        try:
            from anthropic import Anthropic
            anthropic = Anthropic(api_key=anthropic_key)
            
            # Just test connection with minimal tokens
            response = anthropic.messages.create(
                model="claude-3-haiku-20240307",
                max_tokens=1,  # Minimal tokens = minimal cost
                messages=[{"role": "user", "content": "Hi"}]
            )
            
            if response.content and len(response.content) > 0:
                print("✅ Anthropic API is accessible")
                print("💰 Cost: ~$0.0001 (minimal test)")
            else:
                print("❌ No response from Anthropic API")
                
        except Exception as e:
            print(f"❌ Anthropic API error: {e}")
    else:
        print("⚠️  Skipping Anthropic test - no key")
    
    print("\n📋 Summary:")
    print("✅ API keys configured")
    print("✅ Models accessible")
    print("✅ Ready for your hackathon!")
    print("\n💡 Next: Start your FastAPI server and test with real files")

if __name__ == "__main__":
    test_api_connectivity() 
```

### debug_system.py

```python
#!/usr/bin/env python3
"""
Diagnostic script for AI Deepfake Detector
"""

import sys
import os
import requests
import json

def test_backend():
    """Test if backend is running and responding"""
    print("🔍 Testing backend...")
    
    try:
        # Test health endpoint
        response = requests.get("http://localhost:8001/health", timeout=5)
        if response.status_code == 200:
            print("✅ Backend is running")
            return True
        else:
            print(f"❌ Backend returned status {response.status_code}")
            return False
    except requests.exceptions.ConnectionError:
        print("❌ Backend is not running (connection refused)")
        return False
    except Exception as e:
        print(f"❌ Backend test failed: {e}")
        return False

def test_models():
    """Test if models are loaded"""
    print("\n🤖 Testing models...")
    
    try:
        response = requests.get("http://localhost:8001/models", timeout=10)
        if response.status_code == 200:
            models = response.json()
            print("✅ Models endpoint working")
            print(f"📊 Image model: {models.get('image_model', {}).get('name', 'Unknown')}")
            print(f"📊 Audio model: {models.get('audio_model', {}).get('name', 'Unknown')}")
            return True
        else:
            print(f"❌ Models endpoint returned status {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Models test failed: {e}")
        return False

def test_image_upload():
    """Test image upload functionality"""
    print("\n🖼️ Testing image upload...")
    
    try:
        # Create a simple test image (1x1 pixel)
        from PIL import Image
        import io
        
        # Create a tiny test image
        img = Image.new('RGB', (100, 100), color='red')
        img_bytes = io.BytesIO()
        img.save(img_bytes, format='JPEG')
        img_bytes.seek(0)
        
        # Upload to backend
        files = {'file': ('test.jpg', img_bytes, 'image/jpeg')}
        response = requests.post("http://localhost:8001/upload", files=files, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            print("✅ Image upload working")
            print(f"📊 Result: {result.get('is_deepfake', 'Unknown')} ({result.get('confidence', 0):.2f})")
            return True
        else:
            print(f"❌ Image upload failed: {response.status_code}")
            print(f"📄 Response: {response.text}")
            return False
    except Exception as e:
        print(f"❌ Image upload test failed: {e}")
        return False

def check_extension_files():
    """Check if extension files exist"""
    print("\n📁 Checking extension files...")
    
    required_files = [
        'extension/manifest.json',
        'extension/content.js',
        'extension/popup.html',
        'extension/popup.js',
        'extension/content.css',
        'extension/popup.css'
    ]
    
    all_exist = True
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"✅ {file_path}")
        else:
            print(f"❌ {file_path} - MISSING")
            all_exist = False
    
    return all_exist

def main():
    print("🔧 AI Deepfake Detector Diagnostic")
    print("=" * 40)
    
    # Check extension files
    extension_ok = check_extension_files()
    
    # Test backend
    backend_ok = test_backend()
    
    if backend_ok:
        models_ok = test_models()
        upload_ok = test_image_upload()
    else:
        models_ok = False
        upload_ok = False
    
    # Summary
    print("\n📋 Summary:")
    print(f"Extension files: {'✅ OK' if extension_ok else '❌ ISSUES'}")
    print(f"Backend running: {'✅ OK' if backend_ok else '❌ NOT RUNNING'}")
    print(f"Models loaded: {'✅ OK' if models_ok else '❌ ISSUES'}")
    print(f"Image upload: {'✅ OK' if upload_ok else '❌ ISSUES'}")
    
    if not backend_ok:
        print("\n🚨 To start backend: cd backend && python app.py")
    
    if not extension_ok:
        print("\n🚨 Extension files missing - check your installation")
    
    if backend_ok and not upload_ok:
        print("\n🚨 Backend is running but upload failing - check logs")

if __name__ == "__main__":
    main() 
```

### test_extension.py

```python
#!/usr/bin/env python3
"""
Test script for the Chrome extension functionality
Tests the API endpoints that the extension will use
"""

import requests
import json
from PIL import Image
import io
import base64

# Test configuration
API_BASE = "http://localhost:8001"

def test_health_endpoint():
    """Test the health endpoint"""
    print("🔍 Testing health endpoint...")
    try:
        response = requests.get(f"{API_BASE}/health")
        if response.status_code == 200:
            print("✅ Health endpoint working")
            print(f"   Response: {response.json()}")
            return True
        else:
            print(f"❌ Health endpoint failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Health endpoint error: {e}")
        return False

def test_model_info():
    """Test the model info endpoint"""
    print("\n🔍 Testing model info endpoint...")
    try:
        response = requests.get(f"{API_BASE}/models")
        if response.status_code == 200:
            print("✅ Model info endpoint working")
            print(f"   Response: {response.json()}")
            return True
        else:
            print(f"❌ Model info endpoint failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Model info endpoint error: {e}")
        return False

def create_test_image():
    """Create a simple test image"""
    # Create a 384x384 test image with a gradient
    img = Image.new('RGB', (384, 384), color='white')
    pixels = img.load()
    
    # Add a simple gradient
    for i in range(384):
        for j in range(384):
            r = int((i / 384) * 255)
            g = int((j / 384) * 255)
            b = 128
            pixels[i, j] = (r, g, b)
    
    return img

def test_image_upload():
    """Test image upload endpoint"""
    print("\n🔍 Testing image upload endpoint...")
    try:
        # Create test image
        img = create_test_image()
        
        # Convert to bytes
        img_bytes = io.BytesIO()
        img.save(img_bytes, format='JPEG')
        img_bytes.seek(0)
        
        # Prepare file for upload
        files = {'file': ('test_image.jpg', img_bytes, 'image/jpeg')}
        
        # Upload to API
        response = requests.post(f"{API_BASE}/upload", files=files)
        
        if response.status_code == 200:
            result = response.json()
            print("✅ Image upload working")
            print(f"   Is deepfake: {result.get('is_deepfake')}")
            print(f"   Confidence: {result.get('confidence')}")
            print(f"   Processing time: {result.get('processing_time')}")
            print(f"   Model used: {result.get('model_used')}")
            return True
        else:
            print(f"❌ Image upload failed: {response.status_code}")
            print(f"   Response: {response.text}")
            return False
    except Exception as e:
        print(f"❌ Image upload error: {e}")
        return False

def test_cors_headers():
    """Test CORS headers"""
    print("\n🔍 Testing CORS headers...")
    try:
        response = requests.options(f"{API_BASE}/upload")
        cors_headers = response.headers.get('Access-Control-Allow-Origin')
        
        if cors_headers:
            print("✅ CORS headers present")
            print(f"   Allow-Origin: {cors_headers}")
            return True
        else:
            print("❌ CORS headers missing")
            return False
    except Exception as e:
        print(f"❌ CORS test error: {e}")
        return False

def main():
    """Run all tests"""
    print("🚀 Testing Chrome Extension API Integration")
    print("=" * 50)
    
    tests = [
        test_health_endpoint,
        test_model_info,
        test_cors_headers,
        test_image_upload
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        if test():
            passed += 1
    
    print("\n" + "=" * 50)
    print(f"📊 Test Results: {passed}/{total} tests passed")
    
    if passed == total:
        print("🎉 All tests passed! Extension should work correctly.")
        print("\n📋 Next steps:")
        print("1. Load the extension in Chrome (chrome://extensions/)")
        print("2. Enable Developer mode")
        print("3. Click 'Load unpacked' and select the 'extension' folder")
        print("4. Test on a webpage with images")
    else:
        print("⚠️  Some tests failed. Check the backend configuration.")
    
    return passed == total

if __name__ == "__main__":
    main() 
```

### test_detection.py

```python
#!/usr/bin/env python3
"""
Detailed test script for the improved deepfake detection system
Tests different detection types and analysis
"""

import requests
import json
from PIL import Image
import io
import numpy as np

# Test configuration
API_BASE = "http://localhost:8001"

def create_test_images():
    """Create different types of test images"""
    images = {}
    
    # 1. Simple gradient (should be real)
    img_real = Image.new('RGB', (384, 384), color='white')
    pixels = img_real.load()
    for i in range(384):
        for j in range(384):
            r = int((i / 384) * 255)
            g = int((j / 384) * 255)
            b = 128
            pixels[i, j] = (r, g, b)
    images['real'] = img_real
    
    # 2. High contrast image (might trigger AI detection)
    img_contrast = Image.new('RGB', (384, 384), color='black')
    pixels = img_contrast.load()
    for i in range(384):
        for j in range(384):
            if (i + j) % 50 < 25:
                pixels[i, j] = (255, 255, 255)
            else:
                pixels[i, j] = (0, 0, 0)
    images['contrast'] = img_contrast
    
    # 3. Pattern image (similar to thumbnails)
    img_pattern = Image.new('RGB', (384, 384), color='blue')
    pixels = img_pattern.load()
    for i in range(384):
        for j in range(384):
            if (i // 20 + j // 20) % 2 == 0:
                pixels[i, j] = (255, 255, 255)
            else:
                pixels[i, j] = (0, 100, 200)
    images['pattern'] = img_pattern
    
    return images

def test_detection(image, name):
    """Test detection on a specific image"""
    print(f"\n🔍 Testing {name} image...")
    
    try:
        # Convert to bytes
        img_bytes = io.BytesIO()
        image.save(img_bytes, format='JPEG')
        img_bytes.seek(0)
        
        # Prepare file for upload
        files = {'file': (f'{name}_test.jpg', img_bytes, 'image/jpeg')}
        
        # Upload to API
        response = requests.post(f"{API_BASE}/upload", files=files)
        
        if response.status_code == 200:
            result = response.json()
            print(f"✅ {name} detection successful")
            print(f"   Is deepfake: {result.get('is_deepfake')}")
            print(f"   Confidence: {result.get('confidence'):.1%}")
            print(f"   Detection type: {result.get('detection_type', 'unknown')}")
            print(f"   Analysis: {result.get('analysis', 'No analysis')}")
            print(f"   Model note: {result.get('model_note', 'No note')}")
            
            # Show debug info if available
            debug_info = result.get('debug_info', {})
            if debug_info:
                print(f"   Debug - Prediction class: {debug_info.get('prediction_class')}")
                print(f"   Debug - All labels: {debug_info.get('all_labels')}")
                thresholds = debug_info.get('thresholds_used', {})
                print(f"   Debug - Thresholds: {thresholds}")
            
            return result
        else:
            print(f"❌ {name} detection failed: {response.status_code}")
            print(f"   Response: {response.text}")
            return None
    except Exception as e:
        print(f"❌ {name} detection error: {e}")
        return None

def main():
    """Run comprehensive detection tests"""
    print("🧪 Testing Improved Deepfake Detection System")
    print("=" * 60)
    
    # Check if backend is running
    try:
        response = requests.get(f"{API_BASE}/health")
        if not response.ok:
            print("❌ Backend not running. Please start the backend first.")
            return
        print("✅ Backend is running")
    except Exception as e:
        print(f"❌ Cannot connect to backend: {e}")
        return
    
    # Create test images
    print("\n📸 Creating test images...")
    images = create_test_images()
    
    # Test each image
    results = {}
    for name, image in images.items():
        result = test_detection(image, name)
        if result:
            results[name] = result
    
    # Summary
    print("\n" + "=" * 60)
    print("📊 Detection Summary")
    print("=" * 60)
    
    for name, result in results.items():
        detection_type = result.get('detection_type', 'unknown')
        confidence = result.get('confidence', 0)
        is_deepfake = result.get('is_deepfake', False)
        
        status_icon = "🤖" if is_deepfake else "✅"
        print(f"{status_icon} {name:10} | {detection_type:15} | {confidence:5.1%} | {is_deepfake}")
    
    # Analysis
    print("\n💡 Analysis:")
    print("- Real images should be classified as 'real' with high confidence")
    print("- Pattern/contrast images might be flagged as 'possible_ai'")
    print("- Only high-confidence detections should be marked as 'deepfake'")
    print("- Low confidence results should be marked as 'uncertain'")

if __name__ == "__main__":
    main() 
```

### extension/content.css

```css
/* Content script styles for notifications */

.deepfake-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 10000;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    font-size: 14px;
    max-width: 300px;
    animation: slideIn 0.3s ease-out;
}

.notification-content {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    color: white;
}

.notification-icon {
    font-size: 16px;
    line-height: 1;
}

.notification-text {
    flex: 1;
    line-height: 1.2;
}

.notification-close {
    background: none;
    border: none;
    color: white;
    font-size: 18px;
    cursor: pointer;
    padding: 0;
    line-height: 1;
    opacity: 0.8;
    transition: opacity 0.2s;
}

.notification-close:hover {
    opacity: 1;
}

/* Animation keyframes */
@keyframes slideIn {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOut {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

/* AI Content Filter Styles */
.filter-toggle-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}

.filter-toggle-btn {
    background: #666;
    border: none;
    border-radius: 6px;
    padding: 8px 12px;
    color: white;
    cursor: pointer;
    font-size: 12px;
    font-weight: bold;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 6px;
}

.filter-toggle-btn.active {
    background: #ff4444;
    box-shadow: 0 0 10px rgba(255, 68, 68, 0.5);
}

.filter-toggle-btn:hover {
    transform: scale(1.05);
}

.filter-icon {
    font-size: 14px;
}

.filter-text {
    font-weight: bold;
}

.filter-stats {
    font-size: 10px;
    opacity: 0.8;
}

.filter-count {
    font-weight: bold;
    color: #ff4444;
}

/* AI Content Overlay Styles */
.ai-content-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 68, 68, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    border-radius: 8px;
    color: white;
    font-family: Arial, sans-serif;
    text-align: center;
    backdrop-filter: blur(2px);
}

.overlay-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    padding: 16px;
}

.overlay-icon {
    font-size: 32px;
    margin-bottom: 8px;
}

.overlay-text {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 4px;
}

.overlay-confidence {
    font-size: 12px;
    opacity: 0.9;
    margin-bottom: 12px;
}

.overlay-show-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 4px;
    padding: 6px 12px;
    color: white;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s ease;
}

.overlay-show-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.05);
}

/* Animation for filter toggle */
@keyframes filterPulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.filter-toggle-btn.active {
    animation: filterPulse 2s infinite;
} 
```

[12 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]