File size: 7,659 Bytes
547247c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e42a6
547247c
 
 
 
 
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
"""
Document Forgery Detection - Gradio Interface for Hugging Face Spaces

This app provides a web interface for detecting and classifying document forgeries.
"""

import gradio as gr
import torch
import cv2
import numpy as np
from PIL import Image
import json
from pathlib import Path
import sys

# Add src to path
sys.path.insert(0, str(Path(__file__).parent))

from src.models import get_model
from src.config import get_config
from src.data.preprocessing import DocumentPreprocessor
from src.data.augmentation import DatasetAwareAugmentation
from src.features.region_extraction import get_mask_refiner, get_region_extractor
from src.features.feature_extraction import get_feature_extractor
from src.training.classifier import ForgeryClassifier

# Class names
CLASS_NAMES = {0: 'Copy-Move', 1: 'Splicing', 2: 'Generation'}
CLASS_COLORS = {
    0: (255, 0, 0),      # Red for Copy-Move
    1: (0, 255, 0),      # Green for Splicing
    2: (0, 0, 255)       # Blue for Generation
}


class ForgeryDetector:
    """Main forgery detection pipeline"""
    
    def __init__(self):
        print("Loading models...")
        
        # Load config
        self.config = get_config('config.yaml')
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        
        # Load segmentation model
        self.model = get_model(self.config).to(self.device)
        checkpoint = torch.load('models/best_doctamper.pth', map_location=self.device)
        self.model.load_state_dict(checkpoint['model_state_dict'])
        self.model.eval()
        
        # Load classifier
        self.classifier = ForgeryClassifier(self.config)
        self.classifier.load('models/classifier')
        
        # Initialize components
        self.preprocessor = DocumentPreprocessor(self.config, 'doctamper')
        self.augmentation = DatasetAwareAugmentation(self.config, 'doctamper', is_training=False)
        self.mask_refiner = get_mask_refiner(self.config)
        self.region_extractor = get_region_extractor(self.config)
        self.feature_extractor = get_feature_extractor(self.config, is_text_document=True)
        
        print("โœ“ Models loaded successfully!")
    
    def detect(self, image):
        """
        Detect forgeries in document image
        
        Args:
            image: PIL Image or numpy array
            
        Returns:
            overlay_image: Image with detection overlay
            results_json: Detection results as JSON
        """
        # Convert PIL to numpy
        if isinstance(image, Image.Image):
            image = np.array(image)
        
        # Convert to RGB
        if len(image.shape) == 2:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
        elif image.shape[2] == 4:
            image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
        
        original_image = image.copy()
        
        # Preprocess
        preprocessed, _ = self.preprocessor(image, None)
        
        # Augment
        augmented = self.augmentation(preprocessed, None)
        image_tensor = augmented['image'].unsqueeze(0).to(self.device)
        
        # Run localization
        with torch.no_grad():
            logits, decoder_features = self.model(image_tensor)
            prob_map = torch.sigmoid(logits).cpu().numpy()[0, 0]
        
        # Refine mask
        binary_mask = (prob_map > 0.5).astype(np.uint8)
        refined_mask = self.mask_refiner.refine(binary_mask, original_size=original_image.shape[:2])
        
        # Extract regions
        regions = self.region_extractor.extract(refined_mask, prob_map, original_image)
        
        # Classify regions
        results = []
        for region in regions:
            # Extract features
            features = self.feature_extractor.extract(
                preprocessed,
                region['region_mask'],
                [f.cpu() for f in decoder_features]
            )
            
            # Classify
            predictions, confidences = self.classifier.predict(features)
            forgery_type = int(predictions[0])
            confidence = float(confidences[0])
            
            if confidence > 0.6:  # Confidence threshold
                results.append({
                    'region_id': region['region_id'],
                    'bounding_box': region['bounding_box'],
                    'forgery_type': CLASS_NAMES[forgery_type],
                    'confidence': confidence
                })
        
        # Create visualization
        overlay = self._create_overlay(original_image, results)
        
        # Create JSON response
        json_results = {
            'num_detections': len(results),
            'detections': results,
            'model_info': {
                'segmentation_dice': '75%',
                'classifier_accuracy': '92%'
            }
        }
        
        return overlay, json_results
    
    def _create_overlay(self, image, results):
        """Create overlay visualization"""
        overlay = image.copy()
        
        # Draw bounding boxes and labels
        for result in results:
            bbox = result['bounding_box']
            x, y, w, h = bbox
            
            forgery_type = result['forgery_type']
            confidence = result['confidence']
            
            # Get color
            forgery_id = [k for k, v in CLASS_NAMES.items() if v == forgery_type][0]
            color = CLASS_COLORS[forgery_id]
            
            # Draw rectangle
            cv2.rectangle(overlay, (x, y), (x+w, y+h), color, 2)
            
            # Draw label
            label = f"{forgery_type}: {confidence:.1%}"
            label_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 2)
            cv2.rectangle(overlay, (x, y-label_size[1]-10), (x+label_size[0], y), color, -1)
            cv2.putText(overlay, label, (x, y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
        
        # Add legend
        if len(results) > 0:
            legend_y = 30
            cv2.putText(overlay, f"Detected {len(results)} forgery region(s)", 
                       (10, legend_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)
        
        return overlay


# Initialize detector
detector = ForgeryDetector()


def detect_forgery(image):
    """Gradio interface function"""
    try:
        overlay, results = detector.detect(image)
        return overlay, json.dumps(results, indent=2)
    except Exception as e:
        return None, f"Error: {str(e)}"


# Create Gradio interface
demo = gr.Interface(
    fn=detect_forgery,
    inputs=gr.Image(type="pil", label="Upload Document Image"),
    outputs=[
        gr.Image(type="numpy", label="Detection Result"),
        gr.JSON(label="Detection Details")
    ],
    title="๐Ÿ“„ Document Forgery Detector",
    description="""
    Upload a document image to detect and classify forgeries.
    
    **Supported Forgery Types:**
    - ๐Ÿ”ด Copy-Move: Duplicated regions within the document
    - ๐ŸŸข Splicing: Content from different sources
    - ๐Ÿ”ต Generation: AI-generated or synthesized content
    
    **Model Performance:**
    - Localization: 75% Dice Score
    - Classification: 92% Accuracy
    """,
    examples=[
        ["examples/sample1.jpg"],
        ["examples/sample2.jpg"],
    ],
    article="""
    ### About
    This model uses a hybrid deep learning approach:
    1. **Localization**: MobileNetV3-Small + UNet-Lite (detects WHERE)
    2. **Classification**: LightGBM with hybrid features (detects WHAT)
    
    Trained on DocTamper dataset (140K samples).
    """
)


if __name__ == "__main__":
    demo.launch()