LPX
commited on
Commit
·
a1674bb
1
Parent(s):
c14764a
major(refactor): overhaul for ONNX and other optimizations
Browse files- README.md +1 -1
- app_optimized.py +836 -0
- models/model_1_quantized.onnx +0 -3
README.md
CHANGED
@@ -6,7 +6,7 @@ colorFrom: yellow
|
|
6 |
colorTo: yellow
|
7 |
sdk: gradio
|
8 |
sdk_version: 5.33.0
|
9 |
-
app_file:
|
10 |
pinned: true
|
11 |
models:
|
12 |
- aiwithoutborders-xyz/OpenSight-CommunityForensics-Deepfake-ViT
|
|
|
6 |
colorTo: yellow
|
7 |
sdk: gradio
|
8 |
sdk_version: 5.33.0
|
9 |
+
app_file: app_optimized.py
|
10 |
pinned: true
|
11 |
models:
|
12 |
- aiwithoutborders-xyz/OpenSight-CommunityForensics-Deepfake-ViT
|
app_optimized.py
ADDED
@@ -0,0 +1,836 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from gradio_client import Client, handle_file
|
3 |
+
from PIL import Image, ImageFilter
|
4 |
+
import numpy as np
|
5 |
+
import os
|
6 |
+
import time
|
7 |
+
import logging
|
8 |
+
import io
|
9 |
+
import collections
|
10 |
+
import onnxruntime
|
11 |
+
import json
|
12 |
+
from huggingface_hub import CommitScheduler, hf_hub_download, snapshot_download
|
13 |
+
from dotenv import load_dotenv
|
14 |
+
import concurrent.futures
|
15 |
+
|
16 |
+
from utils.utils import softmax, augment_image
|
17 |
+
from forensics.gradient import gradient_processing
|
18 |
+
from forensics.minmax import minmax_process
|
19 |
+
from forensics.ela import ELA
|
20 |
+
from forensics.wavelet import noise_estimation
|
21 |
+
from forensics.bitplane import bit_plane_extractor
|
22 |
+
from utils.hf_logger import log_inference_data
|
23 |
+
from utils.load import load_image
|
24 |
+
from agents.ensemble_team import EnsembleMonitorAgent, WeightOptimizationAgent, SystemHealthAgent
|
25 |
+
from agents.smart_agents import ContextualIntelligenceAgent, ForensicAnomalyDetectionAgent
|
26 |
+
from utils.registry import register_model, MODEL_REGISTRY, ModelEntry
|
27 |
+
from agents.ensemble_weights import ModelWeightManager
|
28 |
+
from transformers import pipeline, AutoImageProcessor, SwinForImageClassification, Swinv2ForImageClassification, AutoFeatureExtractor, AutoModelForImageClassification
|
29 |
+
from torchvision import transforms
|
30 |
+
import torch
|
31 |
+
|
32 |
+
logging.basicConfig(level=logging.INFO)
|
33 |
+
logger = logging.getLogger(__name__)
|
34 |
+
os.environ['HF_HUB_CACHE'] = './models'
|
35 |
+
|
36 |
+
# --- Gradio Log Handler ---
|
37 |
+
class GradioLogHandler(logging.Handler):
|
38 |
+
def __init__(self, log_queue):
|
39 |
+
super().__init__()
|
40 |
+
self.log_queue = log_queue
|
41 |
+
self.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
|
42 |
+
|
43 |
+
def emit(self, record):
|
44 |
+
self.log_queue.append(self.format(record))
|
45 |
+
|
46 |
+
log_queue = collections.deque(maxlen=1000) # Store last 1000 log messages
|
47 |
+
gradio_handler = GradioLogHandler(log_queue)
|
48 |
+
|
49 |
+
# Set root logger level to DEBUG to capture all messages from agents
|
50 |
+
logging.getLogger().setLevel(logging.INFO)
|
51 |
+
logging.getLogger().addHandler(gradio_handler)
|
52 |
+
# --- End Gradio Log Handler ---
|
53 |
+
|
54 |
+
LOCAL_LOG_DIR = "./hf_inference_logs"
|
55 |
+
HF_DATASET_NAME="aiwithoutborders-xyz/degentic_rd0"
|
56 |
+
load_dotenv()
|
57 |
+
|
58 |
+
# Custom JSON Encoder to handle numpy types
|
59 |
+
class NumpyEncoder(json.JSONEncoder):
|
60 |
+
def default(self, obj):
|
61 |
+
if isinstance(obj, np.float32):
|
62 |
+
return float(obj)
|
63 |
+
return json.JSONEncoder.default(self, obj)
|
64 |
+
|
65 |
+
# Ensure using GPU if available
|
66 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
67 |
+
|
68 |
+
# Model paths and class names (copied from app_mcp.py)
|
69 |
+
MODEL_PATHS = {
|
70 |
+
"model_1": "LPX55/detection-model-1-ONNX",
|
71 |
+
"model_2": "LPX55/detection-model-2-ONNX",
|
72 |
+
"model_3": "LPX55/detection-model-3-ONNX",
|
73 |
+
"model_4": "cmckinle/sdxl-flux-detector_v1.1",
|
74 |
+
"model_5": "LPX55/detection-model-5-ONNX",
|
75 |
+
"model_6": "LPX55/detection-model-6-ONNX",
|
76 |
+
"model_7": "LPX55/detection-model-7-ONNX"
|
77 |
+
}
|
78 |
+
|
79 |
+
CLASS_NAMES = {
|
80 |
+
"model_1": ['artificial', 'real'],
|
81 |
+
"model_2": ['AI Image', 'Real Image'],
|
82 |
+
"model_3": ['AI', 'Real'],
|
83 |
+
"model_4": ['AI', 'Real'],
|
84 |
+
"model_5": ['Realism', 'Deepfake'],
|
85 |
+
"model_6": ['ai_gen', 'human'],
|
86 |
+
"model_7": ['Fake', 'Real'],
|
87 |
+
}
|
88 |
+
|
89 |
+
def preprocess_resize_256(image):
|
90 |
+
if image.mode != 'RGB':
|
91 |
+
image = image.convert('RGB')
|
92 |
+
return transforms.Resize((256, 256))(image)
|
93 |
+
|
94 |
+
def preprocess_resize_224(image):
|
95 |
+
if image.mode != 'RGB':
|
96 |
+
image = image.convert('RGB')
|
97 |
+
return transforms.Resize((224, 224))(image)
|
98 |
+
|
99 |
+
def postprocess_pipeline(prediction, class_names):
|
100 |
+
# Assumes HuggingFace pipeline output
|
101 |
+
return {pred['label']: pred['score'] for pred in prediction}
|
102 |
+
|
103 |
+
def postprocess_logits(outputs, class_names):
|
104 |
+
# Assumes model output with logits
|
105 |
+
logits = outputs.logits.cpu().numpy()[0]
|
106 |
+
probabilities = softmax(logits)
|
107 |
+
return {class_names[i]: probabilities[i] for i in range(len(class_names))}
|
108 |
+
|
109 |
+
def register_model_with_metadata(model_id, model, preprocess, postprocess, class_names, display_name, contributor, model_path, architecture=None, dataset=None):
|
110 |
+
entry = ModelEntry(model, preprocess, postprocess, class_names, display_name=display_name, contributor=contributor, model_path=model_path, architecture=architecture, dataset=dataset)
|
111 |
+
MODEL_REGISTRY[model_id] = entry
|
112 |
+
|
113 |
+
|
114 |
+
def load_onnx_model_and_preprocessor(hf_model_id):
|
115 |
+
# model_dir = snapshot_download(repo_id=hf_model_id, local_dir_use_symlinks=False)
|
116 |
+
|
117 |
+
# Create a unique local directory for each ONNX model
|
118 |
+
model_specific_dir = os.path.join("./models", hf_model_id.replace('/', '_'))
|
119 |
+
os.makedirs(model_specific_dir, exist_ok=True)
|
120 |
+
|
121 |
+
# Use hf_hub_download to get specific files into the model-specific directory
|
122 |
+
onnx_model_path = hf_hub_download(repo_id=hf_model_id, filename="model_quantized.onnx", subfolder="onnx", local_dir=model_specific_dir, local_dir_use_symlinks=False)
|
123 |
+
|
124 |
+
# Load preprocessor config
|
125 |
+
preprocessor_config = {}
|
126 |
+
try:
|
127 |
+
preprocessor_config_path = hf_hub_download(repo_id=hf_model_id, filename="preprocessor_config.json", local_dir=model_specific_dir, local_dir_use_symlinks=False)
|
128 |
+
with open(preprocessor_config_path, 'r') as f:
|
129 |
+
preprocessor_config = json.load(f)
|
130 |
+
except Exception as e:
|
131 |
+
logger.warning(f"Could not download or load preprocessor_config.json for {hf_model_id}: {e}")
|
132 |
+
|
133 |
+
# Load model config for class names if available
|
134 |
+
model_config = {}
|
135 |
+
try:
|
136 |
+
model_config_path = hf_hub_download(repo_id=hf_model_id, filename="config.json", local_dir=model_specific_dir, local_dir_use_symlinks=False)
|
137 |
+
with open(model_config_path, 'r') as f:
|
138 |
+
model_config = json.load(f)
|
139 |
+
except Exception as e:
|
140 |
+
logger.warning(f"Could not download or load config.json for {hf_model_id}: {e}")
|
141 |
+
|
142 |
+
return onnxruntime.InferenceSession(onnx_model_path), preprocessor_config, model_config
|
143 |
+
|
144 |
+
|
145 |
+
# Cache for ONNX sessions and preprocessors
|
146 |
+
_onnx_model_cache = {}
|
147 |
+
|
148 |
+
def get_onnx_model_from_cache(hf_model_id):
|
149 |
+
if hf_model_id not in _onnx_model_cache:
|
150 |
+
logger.info(f"Loading ONNX model and preprocessor for {hf_model_id}...")
|
151 |
+
_onnx_model_cache[hf_model_id] = load_onnx_model_and_preprocessor(hf_model_id)
|
152 |
+
return _onnx_model_cache[hf_model_id]
|
153 |
+
|
154 |
+
def preprocess_onnx_input(image: Image.Image, preprocessor_config: dict):
|
155 |
+
# Preprocess image for ONNX model based on preprocessor_config
|
156 |
+
if image.mode != 'RGB':
|
157 |
+
image = image.convert('RGB')
|
158 |
+
|
159 |
+
# Get image size and normalization values from preprocessor_config or use defaults
|
160 |
+
image_size = preprocessor_config.get('size', {'height': 224, 'width': 224})
|
161 |
+
mean = preprocessor_config.get('image_mean', [0.485, 0.456, 0.406])
|
162 |
+
std = preprocessor_config.get('image_std', [0.229, 0.224, 0.225])
|
163 |
+
|
164 |
+
transform = transforms.Compose([
|
165 |
+
transforms.Resize((image_size['height'], image_size['width'])),
|
166 |
+
transforms.ToTensor(),
|
167 |
+
transforms.Normalize(mean=mean, std=std),
|
168 |
+
])
|
169 |
+
input_tensor = transform(image)
|
170 |
+
# ONNX expects numpy array with batch dimension (1, C, H, W)
|
171 |
+
return input_tensor.unsqueeze(0).cpu().numpy()
|
172 |
+
|
173 |
+
def infer_onnx_model(hf_model_id, preprocessed_image_np):
|
174 |
+
try:
|
175 |
+
ort_session, _, _ = get_onnx_model_from_cache(hf_model_id)
|
176 |
+
|
177 |
+
ort_inputs = {ort_session.get_inputs()[0].name: preprocessed_image_np}
|
178 |
+
ort_outputs = ort_session.run(None, ort_inputs)
|
179 |
+
|
180 |
+
# Assuming the output is logits, apply softmax to get probabilities
|
181 |
+
logits = ort_outputs[0]
|
182 |
+
probabilities = softmax(logits[0]) # Remove batch dim, apply softmax
|
183 |
+
return {"logits": logits, "probabilities": probabilities}
|
184 |
+
|
185 |
+
except Exception as e:
|
186 |
+
logger.error(f"Error during ONNX inference for {hf_model_id}: {e}")
|
187 |
+
# Return a structure consistent with other model errors
|
188 |
+
return {"logits": np.array([]), "probabilities": np.array([])}
|
189 |
+
|
190 |
+
def postprocess_onnx_output(onnx_output, model_config):
|
191 |
+
# Get class names from model_config, or use a default if not found
|
192 |
+
class_names = model_config.get('id2label', {0: 'Fake', 1: 'Real'}) # Default to Fake/Real if not found
|
193 |
+
class_names = [class_names[i] for i in sorted(class_names.keys())]
|
194 |
+
|
195 |
+
probabilities = onnx_output.get("probabilities")
|
196 |
+
if probabilities is not None and len(probabilities) == len(class_names):
|
197 |
+
return {class_names[i]: probabilities[i] for i in range(len(class_names))}
|
198 |
+
else:
|
199 |
+
logger.warning("ONNX post-processing failed or class names mismatch.")
|
200 |
+
return {name: 0.0 for name in class_names}
|
201 |
+
|
202 |
+
# Register the ONNX quantized model
|
203 |
+
# Dummy entry for ONNX model to be loaded dynamically
|
204 |
+
# We will now register a 'wrapper' that handles dynamic loading
|
205 |
+
|
206 |
+
class ONNXModelWrapper:
|
207 |
+
def __init__(self, hf_model_id):
|
208 |
+
self.hf_model_id = hf_model_id
|
209 |
+
self._session = None
|
210 |
+
self._preprocessor_config = None
|
211 |
+
self._model_config = None
|
212 |
+
|
213 |
+
def load(self):
|
214 |
+
if self._session is None:
|
215 |
+
self._session, self._preprocessor_config, self._model_config = get_onnx_model_from_cache(self.hf_model_id)
|
216 |
+
logger.info(f"ONNX model {self.hf_model_id} loaded into wrapper.")
|
217 |
+
|
218 |
+
def __call__(self, image_np):
|
219 |
+
self.load() # Ensure model is loaded on first call
|
220 |
+
return infer_onnx_model(self.hf_model_id, image_np)
|
221 |
+
|
222 |
+
def preprocess(self, image: Image.Image):
|
223 |
+
self.load()
|
224 |
+
return preprocess_onnx_input(image, self._preprocessor_config)
|
225 |
+
|
226 |
+
def postprocess(self, onnx_output: dict, class_names_from_registry: list): # class_names_from_registry is ignored
|
227 |
+
self.load()
|
228 |
+
return postprocess_onnx_output(onnx_output, self._model_config)
|
229 |
+
|
230 |
+
# Consolidate all model loading and registration
|
231 |
+
for model_key, hf_model_path in MODEL_PATHS.items():
|
232 |
+
display_name = model_key.replace("model_", "").upper()
|
233 |
+
contributor = "Unknown"
|
234 |
+
architecture = "Unknown"
|
235 |
+
dataset = "TBA"
|
236 |
+
|
237 |
+
# Attempt to derive contributor, architecture, dataset based on model_key
|
238 |
+
if model_key == "model_1":
|
239 |
+
contributor = "haywoodsloan"
|
240 |
+
architecture = "SwinV2"
|
241 |
+
dataset = "DeepFakeDetection"
|
242 |
+
elif model_key == "model_2":
|
243 |
+
contributor = "Heem2"
|
244 |
+
architecture = "ViT"
|
245 |
+
dataset = "DeepFakeDetection"
|
246 |
+
elif model_key == "model_3":
|
247 |
+
contributor = "Organika"
|
248 |
+
architecture = "VIT"
|
249 |
+
dataset = "SDXL"
|
250 |
+
elif model_key == "model_4":
|
251 |
+
contributor = "cmckinle"
|
252 |
+
architecture = "VIT"
|
253 |
+
dataset = "SDXL, FLUX"
|
254 |
+
elif model_key == "model_5":
|
255 |
+
contributor = "prithivMLmods"
|
256 |
+
architecture = "VIT"
|
257 |
+
elif model_key == "model_6":
|
258 |
+
contributor = "ideepankarsharma2003"
|
259 |
+
architecture = "SWINv1"
|
260 |
+
dataset = "SDXL, Midjourney"
|
261 |
+
elif model_key == "model_7":
|
262 |
+
contributor = "date3k2"
|
263 |
+
architecture = "VIT"
|
264 |
+
|
265 |
+
current_class_names = CLASS_NAMES.get(model_key, [])
|
266 |
+
|
267 |
+
if "ONNX" in hf_model_path:
|
268 |
+
logger.info(f"Registering ONNX model: {model_key} from {hf_model_path}")
|
269 |
+
onnx_wrapper_instance = ONNXModelWrapper(hf_model_path)
|
270 |
+
register_model_with_metadata(
|
271 |
+
model_key,
|
272 |
+
onnx_wrapper_instance, # The callable wrapper for the ONNX model
|
273 |
+
onnx_wrapper_instance.preprocess,
|
274 |
+
onnx_wrapper_instance.postprocess,
|
275 |
+
current_class_names, # Initial class names; will be overridden by model_config if available
|
276 |
+
display_name=display_name + ("_ONNX" if "ONNX" not in display_name else ""),
|
277 |
+
contributor=contributor,
|
278 |
+
model_path=hf_model_path,
|
279 |
+
architecture=architecture,
|
280 |
+
dataset=dataset
|
281 |
+
)
|
282 |
+
else:
|
283 |
+
logger.info(f"Registering HuggingFace pipeline/AutoModel: {model_key} from {hf_model_path}")
|
284 |
+
model_instance = None
|
285 |
+
preprocess_func = None
|
286 |
+
postprocess_func = postprocess_pipeline # Default for pipelines
|
287 |
+
current_processor = None
|
288 |
+
|
289 |
+
if model_key == "model_5":
|
290 |
+
model_instance = pipeline("image-classification", model=hf_model_path, device=device)
|
291 |
+
preprocess_func = preprocess_resize_224
|
292 |
+
elif model_key in ["model_3", "model_4"]:
|
293 |
+
current_processor = AutoFeatureExtractor.from_pretrained(hf_model_path, device=device)
|
294 |
+
model_instance = AutoModelForImageClassification.from_pretrained(hf_model_path).to(device)
|
295 |
+
|
296 |
+
preprocess_func = preprocess_resize_256 # Using the shared preprocess_resize_256
|
297 |
+
postprocess_func = postprocess_logits # Using the shared postprocess_logits
|
298 |
+
|
299 |
+
def custom_infer(image, processor_local=current_processor, model_local=model_instance):
|
300 |
+
inputs = processor_local(image, return_tensors="pt").to(device)
|
301 |
+
with torch.no_grad():
|
302 |
+
outputs = model_local(**inputs)
|
303 |
+
return outputs
|
304 |
+
model_instance = custom_infer
|
305 |
+
|
306 |
+
elif model_key in ["model_6", "model_7"]:
|
307 |
+
current_processor = AutoImageProcessor.from_pretrained(hf_model_path, use_fast=True)
|
308 |
+
if model_key == "model_6":
|
309 |
+
model_instance = SwinForImageClassification.from_pretrained(hf_model_path).to(device)
|
310 |
+
else: # model_7
|
311 |
+
model_instance = AutoModelForImageClassification.from_pretrained(hf_model_path).to(device)
|
312 |
+
|
313 |
+
model_instance = pipeline(model=model_instance, task="image-classification", image_processor=current_processor, device=device)
|
314 |
+
preprocess_func = preprocess_resize_224
|
315 |
+
|
316 |
+
if model_instance and preprocess_func:
|
317 |
+
register_model_with_metadata(
|
318 |
+
model_id=model_key,
|
319 |
+
model=model_instance,
|
320 |
+
preprocess=preprocess_func,
|
321 |
+
postprocess=postprocess_func,
|
322 |
+
class_names=current_class_names,
|
323 |
+
display_name=display_name,
|
324 |
+
contributor=contributor,
|
325 |
+
model_path=hf_model_path,
|
326 |
+
architecture=architecture,
|
327 |
+
dataset=dataset
|
328 |
+
)
|
329 |
+
else:
|
330 |
+
logger.warning(f"Could not automatically load and register model: {model_key} from {hf_model_path}")
|
331 |
+
|
332 |
+
|
333 |
+
def infer(image: Image.Image, model_id: str, confidence_threshold: float = 0.75) -> dict:
|
334 |
+
"""Predict using a specific model.
|
335 |
+
|
336 |
+
Args:
|
337 |
+
image (Image.Image): The input image to classify.
|
338 |
+
model_id (str): The ID of the model to use for classification.
|
339 |
+
confidence_threshold (float, optional): The confidence threshold for classification. Defaults to 0.75.
|
340 |
+
|
341 |
+
Returns:
|
342 |
+
dict: A dictionary containing the model details, classification scores, and label.
|
343 |
+
"""
|
344 |
+
entry = MODEL_REGISTRY[model_id]
|
345 |
+
img = entry.preprocess(image) if entry.preprocess else image
|
346 |
+
try:
|
347 |
+
result = entry.model(img)
|
348 |
+
scores = entry.postprocess(result, entry.class_names)
|
349 |
+
ai_score = float(scores.get(entry.class_names[0], 0.0))
|
350 |
+
real_score = float(scores.get(entry.class_names[1], 0.0))
|
351 |
+
label = "AI" if ai_score >= confidence_threshold else ("REAL" if real_score >= confidence_threshold else "UNCERTAIN")
|
352 |
+
return {
|
353 |
+
"Model": entry.display_name,
|
354 |
+
"Contributor": entry.contributor,
|
355 |
+
"HF Model Path": entry.model_path,
|
356 |
+
"AI Score": ai_score,
|
357 |
+
"Real Score": real_score,
|
358 |
+
"Label": label
|
359 |
+
}
|
360 |
+
except Exception as e:
|
361 |
+
return {
|
362 |
+
"Model": entry.display_name,
|
363 |
+
"Contributor": entry.contributor,
|
364 |
+
"HF Model Path": entry.model_path,
|
365 |
+
"AI Score": 0.0,
|
366 |
+
"Real Score": 0.0,
|
367 |
+
"Label": f"Error: {str(e)}"
|
368 |
+
}
|
369 |
+
|
370 |
+
def full_prediction(img, confidence_threshold, rotate_degrees, noise_level, sharpen_strength):
|
371 |
+
"""Full prediction run, with a team of ensembles and agents.
|
372 |
+
|
373 |
+
Args:
|
374 |
+
img (url: str, Image.Image, np.ndarray): The input image to classify.
|
375 |
+
confidence_threshold (float, optional): The confidence threshold for classification. Defaults to 0.75.
|
376 |
+
rotate_degrees (int, optional): The degrees to rotate the image.
|
377 |
+
noise_level (int, optional): The noise level to use.
|
378 |
+
sharpen_strength (int, optional): The sharpen strength to use.
|
379 |
+
|
380 |
+
Returns:
|
381 |
+
dict: A dictionary containing the model details, classification scores, and label.
|
382 |
+
"""
|
383 |
+
# Ensure img is a PIL Image object
|
384 |
+
if img is None:
|
385 |
+
raise gr.Error("No image provided. Please upload an image to analyze.")
|
386 |
+
# Handle filepath conversion if needed
|
387 |
+
if isinstance(img, str):
|
388 |
+
try:
|
389 |
+
img = load_image(img)
|
390 |
+
except Exception as e:
|
391 |
+
logger.error(f"Error loading image from path: {e}")
|
392 |
+
raise gr.Error(f"Could not load image from the provided path. Error: {str(e)}")
|
393 |
+
|
394 |
+
if not isinstance(img, Image.Image):
|
395 |
+
try:
|
396 |
+
img = Image.fromarray(img)
|
397 |
+
except Exception as e:
|
398 |
+
logger.error(f"Error converting input image to PIL: {e}")
|
399 |
+
raise gr.Error("Input image could not be converted to a valid image format. Please try another image.")
|
400 |
+
|
401 |
+
# Ensure image is in RGB format for consistent processing
|
402 |
+
if img.mode != 'RGB':
|
403 |
+
img = img.convert('RGB')
|
404 |
+
|
405 |
+
monitor_agent = EnsembleMonitorAgent()
|
406 |
+
weight_manager = ModelWeightManager(strongest_model_id="simple_prediction")
|
407 |
+
optimization_agent = WeightOptimizationAgent(weight_manager)
|
408 |
+
health_agent = SystemHealthAgent()
|
409 |
+
context_agent = ContextualIntelligenceAgent()
|
410 |
+
anomaly_agent = ForensicAnomalyDetectionAgent()
|
411 |
+
health_agent.monitor_system_health()
|
412 |
+
if rotate_degrees or noise_level or sharpen_strength:
|
413 |
+
img_pil, _ = augment_image(img, ["rotate", "add_noise", "sharpen"], rotate_degrees, noise_level, sharpen_strength)
|
414 |
+
else:
|
415 |
+
img_pil = img
|
416 |
+
img_np_og = np.array(img)
|
417 |
+
|
418 |
+
model_predictions_raw = {}
|
419 |
+
confidence_scores = {}
|
420 |
+
results = []
|
421 |
+
table_rows = []
|
422 |
+
|
423 |
+
# Initialize lists for forensic outputs, starting with the original augmented image
|
424 |
+
cleaned_forensics_images = []
|
425 |
+
forensic_output_descriptions = []
|
426 |
+
|
427 |
+
# Always add the original augmented image first for forensic display
|
428 |
+
if isinstance(img_pil, Image.Image):
|
429 |
+
cleaned_forensics_images.append(img_pil)
|
430 |
+
forensic_output_descriptions.append(f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}")
|
431 |
+
elif isinstance(img_pil, np.ndarray):
|
432 |
+
try:
|
433 |
+
pil_img_from_np = Image.fromarray(img_pil)
|
434 |
+
cleaned_forensics_images.append(pil_img_from_np)
|
435 |
+
forensic_output_descriptions.append(f"Original augmented image (numpy converted to PIL): {pil_img_from_np.width}x{pil_img_from_np.height}")
|
436 |
+
except Exception as e:
|
437 |
+
logger.warning(f"Could not convert original numpy image to PIL for gallery: {e}")
|
438 |
+
|
439 |
+
# Yield initial state with augmented image and empty model predictions
|
440 |
+
yield img_pil, cleaned_forensics_images, table_rows, "[]", "<div style='font-size: 2.2em; font-weight: bold;padding: 10px;'>Consensus: <span style='color:orange'>UNCERTAIN</span></div>"
|
441 |
+
|
442 |
+
|
443 |
+
# Stream results as each model finishes
|
444 |
+
for model_id in MODEL_REGISTRY:
|
445 |
+
model_start = time.time()
|
446 |
+
result = infer(img_pil, model_id, confidence_threshold)
|
447 |
+
model_end = time.time()
|
448 |
+
monitor_agent.monitor_prediction(
|
449 |
+
model_id,
|
450 |
+
result["Label"],
|
451 |
+
max(result.get("AI Score", 0.0), result.get("Real Score", 0.0)),
|
452 |
+
model_end - model_start
|
453 |
+
)
|
454 |
+
model_predictions_raw[model_id] = result
|
455 |
+
confidence_scores[model_id] = max(result.get("AI Score", 0.0), result.get("Real Score", 0.0))
|
456 |
+
results.append(result)
|
457 |
+
table_rows.append([
|
458 |
+
result.get("Model", ""),
|
459 |
+
result.get("Contributor", ""),
|
460 |
+
round(result.get("AI Score", 0.0), 3) if result.get("AI Score") is not None else 0.0,
|
461 |
+
round(result.get("Real Score", 0.0), 3) if result.get("Real Score") is not None else 0.0,
|
462 |
+
result.get("Label", "Error")
|
463 |
+
])
|
464 |
+
# Yield partial results: only update the table, others are None
|
465 |
+
yield None, cleaned_forensics_images, table_rows, None, None # Keep cleaned_forensics_images as is (only augmented image for now)
|
466 |
+
|
467 |
+
# Multi-threaded forensic processing
|
468 |
+
def _run_forensic_task(task_func, img_input, description, **kwargs):
|
469 |
+
try:
|
470 |
+
result_img = task_func(img_input, **kwargs)
|
471 |
+
return result_img, description
|
472 |
+
except Exception as e:
|
473 |
+
logger.error(f"Error processing forensic task {task_func.__name__}: {e}")
|
474 |
+
return None, f"Error processing {description}: {str(e)}"
|
475 |
+
|
476 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
477 |
+
future_ela1 = executor.submit(_run_forensic_task, ELA, img_np_og, "ELA analysis (Pass 1): Grayscale error map, quality 75.", quality=75, scale=50, contrast=20, linear=False, grayscale=True)
|
478 |
+
future_ela2 = executor.submit(_run_forensic_task, ELA, img_np_og, "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.", quality=75, scale=75, contrast=25, linear=False, grayscale=True)
|
479 |
+
future_ela3 = executor.submit(_run_forensic_task, ELA, img_np_og, "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.", quality=75, scale=75, contrast=25, linear=False, grayscale=False)
|
480 |
+
future_gradient1 = executor.submit(_run_forensic_task, gradient_processing, img_np_og, "Gradient processing: Highlights edges and transitions.")
|
481 |
+
future_gradient2 = executor.submit(_run_forensic_task, gradient_processing, img_np_og, "Gradient processing: Int=45, Equalize=True", intensity=45, equalize=True)
|
482 |
+
future_minmax1 = executor.submit(_run_forensic_task, minmax_process, img_np_og, "MinMax processing: Deviations in local pixel values.")
|
483 |
+
future_minmax2 = executor.submit(_run_forensic_task, minmax_process, img_np_og, "MinMax processing (Radius=6): Deviations in local pixel values.", radius=6)
|
484 |
+
|
485 |
+
forensic_futures = [future_ela1, future_ela2, future_ela3, future_gradient1, future_gradient2, future_minmax1, future_minmax2]
|
486 |
+
|
487 |
+
for future in concurrent.futures.as_completed(forensic_futures):
|
488 |
+
processed_img, description = future.result()
|
489 |
+
if processed_img is not None:
|
490 |
+
if isinstance(processed_img, Image.Image):
|
491 |
+
cleaned_forensics_images.append(processed_img)
|
492 |
+
elif isinstance(processed_img, np.ndarray):
|
493 |
+
try:
|
494 |
+
cleaned_forensics_images.append(Image.fromarray(processed_img))
|
495 |
+
except Exception as e:
|
496 |
+
logger.warning(f"Could not convert numpy array to PIL Image for gallery: {e}")
|
497 |
+
else:
|
498 |
+
logger.warning(f"Unexpected type in processed_img from {description}: {type(processed_img)}. Skipping.")
|
499 |
+
|
500 |
+
forensic_output_descriptions.append(description) # Keep track of descriptions for anomaly agent
|
501 |
+
|
502 |
+
# Yield partial results: update gallery
|
503 |
+
yield None, cleaned_forensics_images, table_rows, None, None
|
504 |
+
|
505 |
+
# After all models, compute the rest as before
|
506 |
+
image_data_for_context = {
|
507 |
+
"width": img.width,
|
508 |
+
"height": img.height,
|
509 |
+
"mode": img.mode,
|
510 |
+
}
|
511 |
+
forensic_output_descriptions = [
|
512 |
+
f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
|
513 |
+
"ELA analysis (Pass 1): Grayscale error map, quality 75.",
|
514 |
+
"ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
|
515 |
+
"ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
|
516 |
+
"Gradient processing: Highlights edges and transitions.",
|
517 |
+
"Gradient processing: Int=45, Equalize=True",
|
518 |
+
"MinMax processing: Deviations in local pixel values.",
|
519 |
+
"MinMax processing (Radius=6): Deviations in local pixel values.",
|
520 |
+
# "Bit Plane extractor: Visualization of individual bit planes from different color channels."
|
521 |
+
]
|
522 |
+
detected_context_tags = context_agent.infer_context_tags(image_data_for_context, model_predictions_raw)
|
523 |
+
logger.info(f"Detected context tags: {detected_context_tags}")
|
524 |
+
adjusted_weights = weight_manager.adjust_weights(model_predictions_raw, confidence_scores, context_tags=detected_context_tags)
|
525 |
+
weighted_predictions = {"AI": 0.0, "REAL": 0.0, "UNCERTAIN": 0.0}
|
526 |
+
for model_id, prediction in model_predictions_raw.items():
|
527 |
+
prediction_label = prediction.get("Label")
|
528 |
+
if prediction_label in weighted_predictions:
|
529 |
+
weighted_predictions[prediction_label] += adjusted_weights[model_id]
|
530 |
+
else:
|
531 |
+
logger.warning(f"Unexpected prediction label '{prediction_label}' from model '{model_id}'. Skipping its weight in consensus.")
|
532 |
+
final_prediction_label = "UNCERTAIN"
|
533 |
+
if weighted_predictions["AI"] > weighted_predictions["REAL"] and weighted_predictions["AI"] > weighted_predictions["UNCERTAIN"]:
|
534 |
+
final_prediction_label = "AI"
|
535 |
+
elif weighted_predictions["REAL"] > weighted_predictions["AI"] and weighted_predictions["REAL"] > weighted_predictions["UNCERTAIN"]:
|
536 |
+
final_prediction_label = "REAL"
|
537 |
+
optimization_agent.analyze_performance(final_prediction_label, None)
|
538 |
+
# gradient_image = gradient_processing(img_np_og)
|
539 |
+
# gradient_image2 = gradient_processing(img_np_og, intensity=45, equalize=True)
|
540 |
+
# minmax_image = minmax_process(img_np_og)
|
541 |
+
# minmax_image2 = minmax_process(img_np_og, radius=6)
|
542 |
+
# # bitplane_image = bit_plane_extractor(img_pil)
|
543 |
+
# ela1 = ELA(img_np_og, quality=75, scale=50, contrast=20, linear=False, grayscale=True)
|
544 |
+
# ela2 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=True)
|
545 |
+
# ela3 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=False)
|
546 |
+
# forensics_images = [img_pil, ela1, ela2, ela3, gradient_image, gradient_image2, minmax_image, minmax_image2]
|
547 |
+
# forensic_output_descriptions = [
|
548 |
+
# f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
|
549 |
+
# "ELA analysis (Pass 1): Grayscale error map, quality 75.",
|
550 |
+
# "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
|
551 |
+
# "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
|
552 |
+
# "Gradient processing: Highlights edges and transitions.",
|
553 |
+
# "Gradient processing: Int=45, Equalize=True",
|
554 |
+
# "MinMax processing: Deviations in local pixel values.",
|
555 |
+
# "MinMax processing (Radius=6): Deviations in local pixel values.",
|
556 |
+
# # "Bit Plane extractor: Visualization of individual bit planes from different color channels."
|
557 |
+
# ]
|
558 |
+
anomaly_detection_results = anomaly_agent.analyze_forensic_outputs(forensic_output_descriptions)
|
559 |
+
logger.info(f"Forensic anomaly detection: {anomaly_detection_results['summary']}")
|
560 |
+
consensus_html = f"<div style='font-size: 2.2em; font-weight: bold;padding: 10px;'>Consensus: <span style='color:{'red' if final_prediction_label == 'AI' else ('green' if final_prediction_label == 'REAL' else 'orange')}'>{final_prediction_label}</span></div>"
|
561 |
+
inference_params = {
|
562 |
+
"confidence_threshold": confidence_threshold,
|
563 |
+
"rotate_degrees": rotate_degrees,
|
564 |
+
"noise_level": noise_level,
|
565 |
+
"sharpen_strength": sharpen_strength,
|
566 |
+
"detected_context_tags": detected_context_tags
|
567 |
+
}
|
568 |
+
ensemble_output_data = {
|
569 |
+
"final_prediction_label": final_prediction_label,
|
570 |
+
"weighted_predictions": weighted_predictions,
|
571 |
+
"adjusted_weights": adjusted_weights
|
572 |
+
}
|
573 |
+
agent_monitoring_data_log = {
|
574 |
+
"ensemble_monitor": {
|
575 |
+
"alerts": monitor_agent.alerts,
|
576 |
+
"performance_metrics": monitor_agent.performance_metrics
|
577 |
+
},
|
578 |
+
"weight_optimization": {
|
579 |
+
"prediction_history_length": len(optimization_agent.prediction_history),
|
580 |
+
},
|
581 |
+
"system_health": {
|
582 |
+
"memory_usage": health_agent.health_metrics["memory_usage"],
|
583 |
+
"gpu_utilization": health_agent.health_metrics["gpu_utilization"]
|
584 |
+
},
|
585 |
+
"context_intelligence": {
|
586 |
+
"detected_context_tags": detected_context_tags
|
587 |
+
},
|
588 |
+
"forensic_anomaly_detection": anomaly_detection_results
|
589 |
+
}
|
590 |
+
log_inference_data(
|
591 |
+
original_image=img,
|
592 |
+
inference_params=inference_params,
|
593 |
+
model_predictions=results,
|
594 |
+
ensemble_output=ensemble_output_data,
|
595 |
+
forensic_images=cleaned_forensics_images, # Use the incrementally built list
|
596 |
+
agent_monitoring_data=agent_monitoring_data_log,
|
597 |
+
human_feedback=None
|
598 |
+
)
|
599 |
+
|
600 |
+
logger.info(f"Cleaned forensic images types: {[type(img) for img in cleaned_forensics_images]}")
|
601 |
+
for i, res_dict in enumerate(results):
|
602 |
+
for key in ["AI Score", "Real Score"]:
|
603 |
+
value = res_dict.get(key)
|
604 |
+
if isinstance(value, np.float32):
|
605 |
+
res_dict[key] = float(value)
|
606 |
+
logger.info(f"Converted {key} for result {i} from numpy.float32 to float.")
|
607 |
+
json_results = json.dumps(results, cls=NumpyEncoder)
|
608 |
+
yield img_pil, cleaned_forensics_images, table_rows, json_results, consensus_html
|
609 |
+
|
610 |
+
detection_model_eval_playground = gr.Interface(
|
611 |
+
fn=full_prediction,
|
612 |
+
inputs=[
|
613 |
+
gr.Image(label="Upload Image to Analyze", sources=['upload', 'webcam'], type='filepath'),
|
614 |
+
gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Confidence Threshold"),
|
615 |
+
gr.Slider(0, 45, value=0, step=1, label="Rotate Degrees", visible=False),
|
616 |
+
gr.Slider(0, 50, value=0, step=1, label="Noise Level", visible=False),
|
617 |
+
gr.Slider(0, 50, value=0, step=1, label="Sharpen Strength", visible=False)
|
618 |
+
],
|
619 |
+
outputs=[
|
620 |
+
gr.Image(label="Processed Image", visible=False),
|
621 |
+
gr.Gallery(label="Post Processed Images", visible=True, columns=[4], rows=[2], container=False, height="auto", object_fit="contain", elem_id="post-gallery"),
|
622 |
+
gr.Dataframe(
|
623 |
+
label="Model Predictions",
|
624 |
+
headers=["Arch / Dataset", "By", "AI", "Real", "Label"],
|
625 |
+
datatype=["str", "str", "number", "number", "str"]
|
626 |
+
),
|
627 |
+
gr.JSON(label="Raw Model Results", visible=False),
|
628 |
+
gr.Markdown(label="Consensus", value="")
|
629 |
+
],
|
630 |
+
title="Multi-Model Ensemble + Agentic Coordinated Deepfake Detection (Paper in Progress)",
|
631 |
+
description="The detection of AI-generated images has entered a critical inflection point. While existing solutions struggle with outdated datasets and inflated claims, our approach prioritizes agility, community collaboration, and an offensive approach to deepfake detection.",
|
632 |
+
api_name="predict",
|
633 |
+
live=True # Enable streaming
|
634 |
+
)
|
635 |
+
# def echo_headers(x, request: gr.Request):
|
636 |
+
# print(dict(request.headers))
|
637 |
+
# return str(dict(request.headers))
|
638 |
+
|
639 |
+
|
640 |
+
def predict(img):
|
641 |
+
"""
|
642 |
+
Predicts whether an image is AI-generated or real using the SOTA Community Forensics model.
|
643 |
+
|
644 |
+
Args:
|
645 |
+
img (str): Path to the input image file to analyze.
|
646 |
+
|
647 |
+
Returns:
|
648 |
+
dict: A dictionary containing:
|
649 |
+
- 'Fake Probability' (float): Probability score between 0 and 1 indicating likelihood of being AI-generated
|
650 |
+
- 'Result Description' (str): Human-readable description of the prediction result
|
651 |
+
|
652 |
+
Example:
|
653 |
+
>>> result = predict("path/to/image.jpg")
|
654 |
+
>>> print(result)
|
655 |
+
{'Fake Probability': 0.002, 'Result Description': 'The image is likely real.'}
|
656 |
+
"""
|
657 |
+
client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
|
658 |
+
client.view_api()
|
659 |
+
result = client.predict(
|
660 |
+
handle_file(img),
|
661 |
+
api_name="/simple_predict"
|
662 |
+
)
|
663 |
+
return str(result)
|
664 |
+
community_forensics_preview = gr.Interface(
|
665 |
+
fn=predict,
|
666 |
+
inputs=gr.Image(type="filepath"),
|
667 |
+
outputs=gr.HTML(), # or gr.Markdown() if it's just text
|
668 |
+
title="Quick and simple prediction by our strongest model.",
|
669 |
+
description="No ensemble, no context, no agents, just a quick and simple prediction by our strongest model.",
|
670 |
+
api_name="predict"
|
671 |
+
)
|
672 |
+
|
673 |
+
# leaderboard = gr.Interface(
|
674 |
+
# fn=lambda: "# AI Generated / Deepfake Detection Models Leaderboard: Soon™",
|
675 |
+
# inputs=None,
|
676 |
+
# outputs=gr.Markdown(),
|
677 |
+
# title="Leaderboard",
|
678 |
+
# api_name="leaderboard"
|
679 |
+
# )
|
680 |
+
def simple_prediction(img):
|
681 |
+
"""
|
682 |
+
Quick and simple deepfake or real image prediction by the strongest open-source model on the hub.
|
683 |
+
|
684 |
+
Args:
|
685 |
+
img (str): The input image to analyze, provided as a file path.
|
686 |
+
|
687 |
+
Returns:
|
688 |
+
str: The prediction result stringified from dict. Example: `{'Fake Probability': 0.002, 'Result Description': 'The image is likely real.'}`
|
689 |
+
"""
|
690 |
+
client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
|
691 |
+
client.view_api()
|
692 |
+
client.predict(
|
693 |
+
handle_file(img),
|
694 |
+
api_name="simple_predict"
|
695 |
+
)
|
696 |
+
simple_predict_interface = gr.Interface(
|
697 |
+
fn=simple_prediction,
|
698 |
+
inputs=gr.Image(type="filepath"),
|
699 |
+
outputs=gr.Text(),
|
700 |
+
title="Quick and simple prediction by our strongest model.",
|
701 |
+
description="No ensemble, no context, no agents, just a quick and simple prediction by our strongest model.",
|
702 |
+
api_name="simple_predict"
|
703 |
+
)
|
704 |
+
|
705 |
+
noise_estimation_interface = gr.Interface(
|
706 |
+
fn=noise_estimation,
|
707 |
+
inputs=[gr.Image(type="pil"), gr.Slider(1, 32, value=8, step=1, label="Block Size")],
|
708 |
+
outputs=gr.Image(type="pil"),
|
709 |
+
title="Wavelet-Based Noise Analysis",
|
710 |
+
description="Analyzes image noise patterns using wavelet decomposition. This tool helps detect compression artifacts and artificial noise patterns that may indicate image manipulation. Higher noise levels in specific regions can reveal areas of potential tampering.",
|
711 |
+
api_name="tool_waveletnoise"
|
712 |
+
)
|
713 |
+
|
714 |
+
bit_plane_interface = gr.Interface(
|
715 |
+
fn=bit_plane_extractor,
|
716 |
+
inputs=[
|
717 |
+
gr.Image(type="pil"),
|
718 |
+
gr.Dropdown(["Luminance", "Red", "Green", "Blue", "RGB Norm"], label="Channel", value="Luminance"),
|
719 |
+
gr.Slider(0, 7, value=0, step=1, label="Bit Plane"),
|
720 |
+
gr.Dropdown(["Disabled", "Median", "Gaussian"], label="Filter", value="Disabled")
|
721 |
+
],
|
722 |
+
outputs=gr.Image(type="pil"),
|
723 |
+
title="Bit Plane Analysis",
|
724 |
+
description="Extracts and visualizes individual bit planes from different color channels. This forensic tool helps identify hidden patterns and artifacts in image data that may indicate manipulation. Different bit planes can reveal inconsistencies in image processing or editing.",
|
725 |
+
api_name="tool_bitplane"
|
726 |
+
)
|
727 |
+
|
728 |
+
ela_interface = gr.Interface(
|
729 |
+
fn=ELA,
|
730 |
+
inputs=[
|
731 |
+
gr.Image(type="pil", label="Input Image"),
|
732 |
+
gr.Slider(1, 100, value=75, step=1, label="JPEG Quality"),
|
733 |
+
gr.Slider(1, 100, value=50, step=1, label="Output Scale (Multiplicative Gain)"),
|
734 |
+
gr.Slider(0, 100, value=20, step=1, label="Output Contrast (Tonality Compression)"),
|
735 |
+
gr.Checkbox(value=False, label="Use Linear Difference"),
|
736 |
+
gr.Checkbox(value=False, label="Grayscale Output")
|
737 |
+
],
|
738 |
+
outputs=gr.Image(type="pil"),
|
739 |
+
title="Error Level Analysis (ELA)",
|
740 |
+
description="Performs Error Level Analysis to detect re-saved JPEG images, which can indicate tampering. ELA highlights areas of an image that have different compression levels.",
|
741 |
+
api_name="tool_ela"
|
742 |
+
)
|
743 |
+
|
744 |
+
gradient_processing_interface = gr.Interface(
|
745 |
+
fn=gradient_processing,
|
746 |
+
inputs=[
|
747 |
+
gr.Image(type="pil", label="Input Image"),
|
748 |
+
gr.Slider(0, 100, value=90, step=1, label="Intensity"),
|
749 |
+
gr.Dropdown(["Abs", "None", "Flat", "Norm"], label="Blue Mode", value="Abs"),
|
750 |
+
gr.Checkbox(value=False, label="Invert Gradients"),
|
751 |
+
gr.Checkbox(value=False, label="Equalize Histogram")
|
752 |
+
],
|
753 |
+
outputs=gr.Image(type="pil"),
|
754 |
+
title="Gradient Processing",
|
755 |
+
description="Applies gradient filters to an image to enhance edges and transitions, which can reveal inconsistencies due to manipulation.",
|
756 |
+
api_name="tool_gradient_processing"
|
757 |
+
)
|
758 |
+
|
759 |
+
minmax_processing_interface = gr.Interface(
|
760 |
+
fn=minmax_process,
|
761 |
+
inputs=[
|
762 |
+
gr.Image(type="pil", label="Input Image"),
|
763 |
+
gr.Radio([0, 1, 2, 3, 4], label="Channel (0:Grayscale, 1:Blue, 2:Green, 3:Red, 4:RGB Norm)", value=4),
|
764 |
+
gr.Slider(0, 10, value=2, step=1, label="Radius")
|
765 |
+
],
|
766 |
+
outputs=gr.Image(type="pil"),
|
767 |
+
title="MinMax Processing",
|
768 |
+
description="Analyzes local pixel value deviations to detect subtle changes in image data, often indicative of digital forgeries.",
|
769 |
+
api_name="tool_minmax_processing"
|
770 |
+
)
|
771 |
+
|
772 |
+
# augmentation_tool_interface = gr.Interface(
|
773 |
+
# fn=augment_image,
|
774 |
+
# inputs=[
|
775 |
+
# gr.Image(label="Upload Image to Augment", sources=['upload', 'webcam'], type='pil'),
|
776 |
+
# gr.CheckboxGroup(["rotate", "add_noise", "sharpen"], label="Augmentation Methods"),
|
777 |
+
# gr.Slider(0, 360, value=0, step=1, label="Rotate Degrees", visible=True),
|
778 |
+
# gr.Slider(0, 100, value=0, step=1, label="Noise Level", visible=True),
|
779 |
+
# gr.Slider(0, 200, value=1, step=1, label="Sharpen Strength", visible=True)
|
780 |
+
# ],
|
781 |
+
# outputs=gr.Image(label="Augmented Image", type='pil'),
|
782 |
+
# title="Image Augmentation Tool",
|
783 |
+
# description="Apply various augmentation techniques to your image.",
|
784 |
+
# api_name="augment_image"
|
785 |
+
# )
|
786 |
+
|
787 |
+
# def get_captured_logs():
|
788 |
+
# # Retrieve all logs from the queue and clear it
|
789 |
+
# logs = list(log_queue)
|
790 |
+
# log_queue.clear() # Clear the queue after retrieving
|
791 |
+
# return "\n".join(logs)
|
792 |
+
|
793 |
+
|
794 |
+
demo = gr.TabbedInterface(
|
795 |
+
[
|
796 |
+
detection_model_eval_playground,
|
797 |
+
community_forensics_preview,
|
798 |
+
noise_estimation_interface,
|
799 |
+
bit_plane_interface,
|
800 |
+
ela_interface,
|
801 |
+
gradient_processing_interface,
|
802 |
+
minmax_processing_interface,
|
803 |
+
# gr.Textbox(label="Agent Logs", interactive=False, lines=5, max_lines=20, autoscroll=True) # New textbox for logs
|
804 |
+
],
|
805 |
+
[
|
806 |
+
"Run Ensemble Prediction",
|
807 |
+
"Open-Source SOTA Model",
|
808 |
+
"Wavelet Blocking Noise Estimation",
|
809 |
+
"Bit Plane Values",
|
810 |
+
"Error Level Analysis (ELA)",
|
811 |
+
"Gradient Processing",
|
812 |
+
"MinMax Processing",
|
813 |
+
# "Agent Logs" # New tab title
|
814 |
+
],
|
815 |
+
title="Deepfake Detection & Forensics Tools",
|
816 |
+
theme=None,
|
817 |
+
|
818 |
+
)
|
819 |
+
footerMD = """
|
820 |
+
### ⚠️ ENSEMBLE TEAM IN TRAINING ⚠️ \n\n
|
821 |
+
|
822 |
+
1. **DISCLAIMER: METADATA AS WELL AS MEDIA SUBMITTED TO THIS SPACE MAY BE VIEWED AND SELECTED FOR FUTURE DATASETS, PLEASE DO NOT SUBMIT PERSONAL CONTENT. FOR UNTRACKED, PRIVATE USE OF THE MODELS YOU MAY STILL USE [THE ORIGINAL SPACE HERE](https://huggingface.co/spaces/aiwithoutborders-xyz/OpenSight-Deepfake-Detection-Models-Playground), SOTA MODEL INCLUDED.**
|
823 |
+
2. **UPDATE 6-13-25**: APOLOGIES FOR THE CONFUSION, WE ARE WORKING TO REVERT THE ORIGINAL REPO BACK TO ITS NON-DATA COLLECTION STATE -- ONLY THE "SIMPLE PREDICTION" ENDPOINT IS CURRENTLY 100% PRIVATE. PLEASE STAY TUNED AS WE FIGURE OUT A SOLUTION FOR THE ENSEMBLE + AGENT TEAM ENDPOINT. IT CAN GET RESOURCE INTENSIVE TO RUN A FULL PREDICTION. ALTERNATIVELY, WE **ENCOURAGE** ANYONE TO FORK AND CONTRIBUTE TO THE PROJECT.
|
824 |
+
3. **UPDATE 6-13-25 (cont.)**: WHILE WE HAVE NOT TAKEN A STANCE ON NSFW AND EXPLICIT CONTENT, PLEASE REFRAIN FROM ... YOUR HUMAN DESIRES UNTIL WE GET THIS PRIVACY SITUATION SORTED OUT. DO NOT BE RECKLESS PLEASE. OUR PAPER WILL BE OUT SOON ON ARXIV WHICH WILL EXPLAIN EVERYTHING WITH DATA-BACKED RESEARCH ON WHY THIS PROJECT IS NEEDED, BUT WE CANNOT DO IT WITHOUT THE HELP OF THE COMMUNITY.
|
825 |
+
|
826 |
+
TO SUMMARIZE: DATASET COLLECTION WILL CONTINUE FOR OUR NOVEL ENSEMBLE-TEAM PREDICTION PIPELINE UNTIL WE CAN GET THINGS SORTED OUT. FOR THOSE THAT WISH TO OPT-OUT, WE OFFER THE SIMPLE, BUT [MOST POWERFUL DETECTION MODEL HERE.](https://huggingface.co/spaces/aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview)
|
827 |
+
|
828 |
+
"""
|
829 |
+
footer = gr.Markdown("", elem_classes="footer")
|
830 |
+
|
831 |
+
with gr.Blocks() as app:
|
832 |
+
demo.render()
|
833 |
+
footer.render()
|
834 |
+
|
835 |
+
|
836 |
+
app.queue(max_size=10, default_concurrency_limit=2).launch(mcp_server=True)
|
models/model_1_quantized.onnx
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:ecf6b2bb01362d913ea6d8ebcb3d8a8544b41014e663b53b9b89f868401c6f7b
|
3 |
-
size 321926825
|
|
|
|
|
|
|
|