LPX55 commited on
Commit
f7bb227
·
verified ·
1 Parent(s): 99b6d79

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +676 -0
app.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import ast
16
+ import torch
17
+ from gradio_log import Log
18
+ from pathlib import Path
19
+
20
+ from utils.utils import softmax, augment_image, preprocess_resize_256, preprocess_resize_224, postprocess_pipeline, postprocess_logits, postprocess_binary_output, to_float_scalar, infer_gradio_api, preprocess_gradio_api, postprocess_gradio_api
21
+ from utils.onnx_helpers import preprocess_onnx_input, postprocess_onnx_output, infer_onnx_model
22
+ from utils.model_loader import register_all_models
23
+ from utils.onnx_model_loader import load_onnx_model_and_preprocessor, get_onnx_model_from_cache
24
+ from forensics.gradient import gradient_processing
25
+ from forensics.minmax import minmax_process
26
+ from forensics.ela import ELA
27
+ from forensics.wavelet import noise_estimation
28
+ from forensics.bitplane import bit_plane_extractor
29
+ from forensics.jpeg_compression import estimate_qf
30
+ from utils.hf_logger import log_inference_data
31
+ from utils.load import load_image
32
+ from agents.ensemble_team import EnsembleMonitorAgent, WeightOptimizationAgent, SystemHealthAgent
33
+ from agents.smart_agents import ContextualIntelligenceAgent, ForensicAnomalyDetectionAgent
34
+ from utils.registry import register_model, MODEL_REGISTRY, ModelEntry
35
+ from agents.ensemble_weights import ModelWeightManager
36
+ from transformers import pipeline, AutoImageProcessor, SwinForImageClassification, Swinv2ForImageClassification, AutoFeatureExtractor, AutoModelForImageClassification
37
+ from torchvision import transforms
38
+ load_dotenv()
39
+ logging.basicConfig(level=logging.INFO)
40
+ logger = logging.getLogger(__name__)
41
+ os.environ['HF_HUB_CACHE'] = './models'
42
+
43
+
44
+ # --- Gradio Log Handler ---
45
+
46
+ # --- Per-Agent Logging Setup ---
47
+ from utils.agent_logger import AgentLogger, AGENT_LOG_FILES
48
+ agent_logger = AgentLogger()
49
+ # --- End Per-Agent Logging Setup ---
50
+
51
+ LOCAL_LOG_DIR = "./hf_inference_logs"
52
+ HF_DATASET_NAME="aiwithoutborders-xyz/degentic_rd0"
53
+
54
+
55
+
56
+ # Custom JSON Encoder to handle numpy types
57
+ class NumpyEncoder(json.JSONEncoder):
58
+ def default(self, obj):
59
+ if isinstance(obj, np.float32):
60
+ return float(obj)
61
+ return json.JSONEncoder.default(self, obj)
62
+
63
+ # Ensure using GPU if available
64
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
65
+
66
+ # Model paths and class names (copied from app_mcp.py)
67
+ # MODEL_PATHS (model_4 removed)
68
+ MODEL_PATHS = {
69
+ "model_1": "LPX55/detection-model-1-ONNX",
70
+ "model_2": "LPX55/detection-model-2-ONNX",
71
+ "model_3": "LPX55/detection-model-3-ONNX",
72
+ "model_5": "LPX55/detection-model-5-ONNX",
73
+ "model_6": "LPX55/detection-model-6-ONNX",
74
+ "model_7": "LPX55/detection-model-7-ONNX",
75
+ "model_8": "aiwithoutborders-xyz/CommunityForensics-DeepfakeDet-ViT"
76
+ }
77
+
78
+ # CLASS_NAMES (model_4 removed)
79
+ CLASS_NAMES = {
80
+ "model_1": ['artificial', 'real'],
81
+ "model_2": ['AI Image', 'Real Image'],
82
+ "model_3": ['artificial', 'human'],
83
+ "model_5": ['Realism', 'Deepfake'],
84
+ "model_6": ['ai_gen', 'human'],
85
+ "model_7": ['Fake', 'Real'],
86
+ "model_8": ['Fake', 'Real'],
87
+ }
88
+
89
+
90
+ def register_model_with_metadata(model_id, model, preprocess, postprocess, class_names, display_name, contributor, model_path, architecture=None, dataset=None):
91
+ entry = ModelEntry(model, preprocess, postprocess, class_names, display_name=display_name, contributor=contributor, model_path=model_path, architecture=architecture, dataset=dataset)
92
+ MODEL_REGISTRY[model_id] = entry
93
+
94
+
95
+
96
+ # Cache for ONNX sessions and preprocessors
97
+ _onnx_model_cache = {}
98
+
99
+
100
+
101
+ # Register all models (ONNX, HuggingFace, Gradio API)
102
+ register_all_models(MODEL_PATHS, CLASS_NAMES, device, infer_onnx_model, preprocess_onnx_input, postprocess_onnx_output)
103
+
104
+ # Register the ONNX quantized model
105
+ # Dummy entry for ONNX model to be loaded dynamically
106
+ # We will now register a 'wrapper' that handles dynamic loading
107
+
108
+
109
+
110
+
111
+ def infer(image: Image.Image, model_id: str, confidence_threshold: float = 0.75) -> dict:
112
+ """Predict using a specific model.
113
+
114
+ Args:
115
+ image (Image.Image): The input image to classify.
116
+ model_id (str): The ID of the model to use for classification.
117
+ confidence_threshold (float, optional): The confidence threshold for classification. Defaults to 0.75.
118
+
119
+ Returns:
120
+ dict: A dictionary containing the model details, classification scores, and label.
121
+ """
122
+ entry = MODEL_REGISTRY[model_id]
123
+ img = entry.preprocess(image) if entry.preprocess else image
124
+ try:
125
+ result = entry.model(img)
126
+ scores = entry.postprocess(result, entry.class_names)
127
+
128
+ def _to_float_scalar(value):
129
+ if isinstance(value, np.ndarray):
130
+ return float(value.item()) # Convert numpy array scalar to Python float
131
+ return float(value) # Already a Python scalar or convertible type
132
+
133
+ ai_score = _to_float_scalar(scores.get(entry.class_names[0], 0.0))
134
+ real_score = _to_float_scalar(scores.get(entry.class_names[1], 0.0))
135
+ label = "AI" if ai_score >= confidence_threshold else ("REAL" if real_score >= confidence_threshold else "UNCERTAIN")
136
+ return {
137
+ "Model": entry.display_name,
138
+ "Contributor": entry.contributor,
139
+ "HF Model Path": entry.model_path,
140
+ "AI Score": ai_score,
141
+ "Real Score": real_score,
142
+ "Label": label
143
+ }
144
+ except Exception as e:
145
+ return {
146
+ "Model": entry.display_name,
147
+ "Contributor": entry.contributor,
148
+ "HF Model Path": entry.model_path,
149
+ "AI Score": 0.0,
150
+ "Real Score": 0.0,
151
+ "Label": f"Error: {str(e)}"
152
+ }
153
+
154
+ def full_prediction(img, confidence_threshold, rotate_degrees, noise_level, sharpen_strength):
155
+ """Full prediction run, with a team of ensembles and agents.
156
+
157
+ Args:
158
+ img (url: str, Image.Image, np.ndarray): The input image to classify.
159
+ confidence_threshold (float, optional): The confidence threshold for classification. Defaults to 0.75.
160
+ rotate_degrees (int, optional): The degrees to rotate the image.
161
+ noise_level (int, optional): The noise level to use.
162
+ sharpen_strength (int, optional): The sharpen strength to use.
163
+
164
+ Returns:
165
+ dict: A dictionary containing the model details, classification scores, and label.
166
+ """
167
+ # Ensure img is a PIL Image object
168
+ if img is None:
169
+ raise gr.Error("No image provided. Please upload an image to analyze.")
170
+ # Handle filepath conversion if needed
171
+ if isinstance(img, str):
172
+ try:
173
+ img = load_image(img)
174
+ except Exception as e:
175
+ logger.error(f"Error loading image from path: {e}")
176
+ raise gr.Error(f"Could not load image from the provided path. Error: {str(e)}")
177
+
178
+ if not isinstance(img, Image.Image):
179
+ try:
180
+ img = Image.fromarray(img)
181
+ except Exception as e:
182
+ logger.error(f"Error converting input image to PIL: {e}")
183
+ raise gr.Error("Input image could not be converted to a valid image format. Please try another image.")
184
+
185
+ # Ensure image is in RGB format for consistent processing
186
+ if img.mode != 'RGB':
187
+ img = img.convert('RGB')
188
+
189
+ monitor_agent = EnsembleMonitorAgent()
190
+ weight_manager = ModelWeightManager(strongest_model_id="model_8")
191
+ optimization_agent = WeightOptimizationAgent(weight_manager)
192
+ health_agent = SystemHealthAgent()
193
+ context_agent = ContextualIntelligenceAgent()
194
+ anomaly_agent = ForensicAnomalyDetectionAgent()
195
+ health_agent.monitor_system_health()
196
+ if rotate_degrees or noise_level or sharpen_strength:
197
+ img_pil, _ = augment_image(img, ["rotate", "add_noise", "sharpen"], rotate_degrees, noise_level, sharpen_strength)
198
+ else:
199
+ img_pil = img
200
+ img_np_og = np.array(img)
201
+
202
+ model_predictions_raw = {}
203
+ confidence_scores = {}
204
+ results = []
205
+ table_rows = []
206
+
207
+ # Initialize lists for forensic outputs, starting with the original augmented image
208
+ cleaned_forensics_images = []
209
+ forensic_output_descriptions = []
210
+
211
+ # Always add the original augmented image first for forensic display
212
+ if isinstance(img_pil, Image.Image):
213
+ cleaned_forensics_images.append(img_pil)
214
+ forensic_output_descriptions.append(f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}")
215
+ elif isinstance(img_pil, np.ndarray):
216
+ try:
217
+ pil_img_from_np = Image.fromarray(img_pil)
218
+ cleaned_forensics_images.append(pil_img_from_np)
219
+ forensic_output_descriptions.append(f"Original augmented image (numpy converted to PIL): {pil_img_from_np.width}x{pil_img_from_np.height}")
220
+ except Exception as e:
221
+ logger.warning(f"Could not convert original numpy image to PIL for gallery: {e}")
222
+
223
+ # Yield initial state with augmented image and empty model predictions
224
+ 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>", None, None, None, None, None
225
+
226
+
227
+ # Stream results as each model finishes
228
+ for model_id in MODEL_REGISTRY:
229
+ model_start = time.time()
230
+ result = infer(img_pil, model_id, confidence_threshold)
231
+ model_end = time.time()
232
+
233
+ # Helper to ensure values are Python floats, handling numpy scalars
234
+ def _ensure_float_scalar(value):
235
+ if isinstance(value, np.ndarray):
236
+ return float(value.item()) # Convert numpy array scalar to Python float
237
+ return float(value) # Already a Python scalar or convertible type
238
+
239
+ ai_score_val = _ensure_float_scalar(result.get("AI Score", 0.0))
240
+ real_score_val = _ensure_float_val = _ensure_float_scalar(result.get("Real Score", 0.0))
241
+
242
+ monitor_agent.monitor_prediction(
243
+ model_id,
244
+ result["Label"],
245
+ max(ai_score_val, real_score_val),
246
+ model_end - model_start
247
+ )
248
+ model_predictions_raw[model_id] = result
249
+ confidence_scores[model_id] = max(ai_score_val, real_score_val)
250
+ results.append(result)
251
+ table_rows.append([
252
+ result.get("Model", ""),
253
+ result.get("Contributor", ""),
254
+ round(ai_score_val, 5),
255
+ round(real_score_val, 5),
256
+ result.get("Label", "Error")
257
+ ])
258
+ # Yield partial results: only update the table, others are None
259
+ yield None, cleaned_forensics_images, table_rows, None, None, None, None, None, None, None # Keep cleaned_forensics_images as is (only augmented image for now)
260
+
261
+ # Multi-threaded forensic processing
262
+ def _run_forensic_task(task_func, img_input, description, **kwargs):
263
+ try:
264
+ result_img = task_func(img_input, **kwargs)
265
+ return result_img, description
266
+ except Exception as e:
267
+ logger.error(f"Error processing forensic task {task_func.__name__}: {e}")
268
+ return None, f"Error processing {description}: {str(e)}"
269
+
270
+ with concurrent.futures.ThreadPoolExecutor() as executor:
271
+ 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)
272
+ 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)
273
+ 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)
274
+ future_gradient1 = executor.submit(_run_forensic_task, gradient_processing, img_np_og, "Gradient processing: Highlights edges and transitions.")
275
+ future_gradient2 = executor.submit(_run_forensic_task, gradient_processing, img_np_og, "Gradient processing: Int=45, Equalize=True", intensity=45, equalize=True)
276
+ future_minmax1 = executor.submit(_run_forensic_task, minmax_process, img_np_og, "MinMax processing: Deviations in local pixel values.")
277
+ future_minmax2 = executor.submit(_run_forensic_task, minmax_process, img_np_og, "MinMax processing (Radius=6): Deviations in local pixel values.", radius=6)
278
+
279
+ forensic_futures = [future_ela1, future_ela2, future_ela3, future_gradient1, future_gradient2, future_minmax1, future_minmax2]
280
+
281
+ for future in concurrent.futures.as_completed(forensic_futures):
282
+ processed_img, description = future.result()
283
+ if processed_img is not None:
284
+ if isinstance(processed_img, Image.Image):
285
+ cleaned_forensics_images.append(processed_img)
286
+ elif isinstance(processed_img, np.ndarray):
287
+ try:
288
+ cleaned_forensics_images.append(Image.fromarray(processed_img))
289
+ except Exception as e:
290
+ logger.warning(f"Could not convert numpy array to PIL Image for gallery: {e}")
291
+ else:
292
+ logger.warning(f"Unexpected type in processed_img from {description}: {type(processed_img)}. Skipping.")
293
+
294
+ forensic_output_descriptions.append(description) # Keep track of descriptions for anomaly agent
295
+
296
+ # Yield partial results: update gallery
297
+ yield None, cleaned_forensics_images, table_rows, None, None, None, None, None, None, None
298
+
299
+ # After all models, compute the rest as before
300
+ image_data_for_context = {
301
+ "width": img.width,
302
+ "height": img.height,
303
+ "mode": img.mode,
304
+ }
305
+ forensic_output_descriptions = [
306
+ f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
307
+ "ELA analysis (Pass 1): Grayscale error map, quality 75.",
308
+ "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
309
+ "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
310
+ "Gradient processing: Highlights edges and transitions.",
311
+ "Gradient processing: Int=45, Equalize=True",
312
+ "MinMax processing: Deviations in local pixel values.",
313
+ "MinMax processing (Radius=6): Deviations in local pixel values.",
314
+ # "Bit Plane extractor: Visualization of individual bit planes from different color channels."
315
+ ]
316
+ detected_context_tags = context_agent.infer_context_tags(image_data_for_context, model_predictions_raw)
317
+ agent_logger.log("context_intelligence", "info", f"Detected context tags: {detected_context_tags}")
318
+ adjusted_weights = weight_manager.adjust_weights(model_predictions_raw, confidence_scores, context_tags=detected_context_tags)
319
+ weighted_predictions = {"AI": 0.0, "REAL": 0.0, "UNCERTAIN": 0.0}
320
+ for model_id, prediction in model_predictions_raw.items():
321
+ prediction_label = prediction.get("Label")
322
+ if prediction_label in weighted_predictions:
323
+ weighted_predictions[prediction_label] += adjusted_weights[model_id]
324
+ else:
325
+ logger.warning(f"Unexpected prediction label '{prediction_label}' from model '{model_id}'. Skipping its weight in consensus.")
326
+ final_prediction_label = "UNCERTAIN"
327
+ if weighted_predictions["AI"] > weighted_predictions["REAL"] and weighted_predictions["AI"] > weighted_predictions["UNCERTAIN"]:
328
+ final_prediction_label = "AI"
329
+ elif weighted_predictions["REAL"] > weighted_predictions["AI"] and weighted_predictions["REAL"] > weighted_predictions["UNCERTAIN"]:
330
+ final_prediction_label = "REAL"
331
+ optimization_agent.analyze_performance(final_prediction_label, None)
332
+ # gradient_image = gradient_processing(img_np_og)
333
+ # gradient_image2 = gradient_processing(img_np_og, intensity=45, equalize=True)
334
+ # minmax_image = minmax_process(img_np_og)
335
+ # minmax_image2 = minmax_process(img_np_og, radius=6)
336
+ # # bitplane_image = bit_plane_extractor(img_pil)
337
+ # ela1 = ELA(img_np_og, quality=75, scale=50, contrast=20, linear=False, grayscale=True)
338
+ # ela2 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=True)
339
+ # ela3 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=False)
340
+ # forensics_images = [img_pil, ela1, ela2, ela3, gradient_image, gradient_image2, minmax_image, minmax_image2]
341
+ # forensic_output_descriptions = [
342
+ # f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
343
+ # "ELA analysis (Pass 1): Grayscale error map, quality 75.",
344
+ # "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
345
+ # "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
346
+ # "Gradient processing: Highlights edges and transitions.",
347
+ # "Gradient processing: Int=45, Equalize=True",
348
+ # "MinMax processing: Deviations in local pixel values.",
349
+ # "MinMax processing (Radius=6): Deviations in local pixel values.",
350
+ # # "Bit Plane extractor: Visualization of individual bit planes from different color channels."
351
+ # ]
352
+
353
+ anomaly_detection_results = anomaly_agent.analyze_forensic_outputs(forensic_output_descriptions)
354
+ agent_logger.log("forensic_anomaly_detection", "info", f"Forensic anomaly detection: {anomaly_detection_results['summary']}")
355
+ 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>"
356
+ inference_params = {
357
+ "confidence_threshold": confidence_threshold,
358
+ "rotate_degrees": rotate_degrees,
359
+ "noise_level": noise_level,
360
+ "sharpen_strength": sharpen_strength,
361
+ "detected_context_tags": detected_context_tags
362
+ }
363
+ ensemble_output_data = {
364
+ "final_prediction_label": final_prediction_label,
365
+ "weighted_predictions": weighted_predictions,
366
+ "adjusted_weights": adjusted_weights
367
+ }
368
+ agent_monitoring_data_log = {
369
+ "ensemble_monitor": {
370
+ "alerts": monitor_agent.alerts,
371
+ "performance_metrics": monitor_agent.performance_metrics
372
+ },
373
+ "weight_optimization": {
374
+ "prediction_history_length": len(optimization_agent.prediction_history),
375
+ },
376
+ "system_health": {
377
+ "memory_usage": health_agent.health_metrics["memory_usage"],
378
+ "gpu_utilization": health_agent.health_metrics["gpu_utilization"]
379
+ },
380
+ "context_intelligence": {
381
+ "detected_context_tags": detected_context_tags
382
+ },
383
+ "forensic_anomaly_detection": anomaly_detection_results
384
+ }
385
+ log_inference_data(
386
+ original_image=img,
387
+ inference_params=inference_params,
388
+ model_predictions=results,
389
+ ensemble_output=ensemble_output_data,
390
+ forensic_images=cleaned_forensics_images, # Use the incrementally built list
391
+ agent_monitoring_data=agent_monitoring_data_log,
392
+ human_feedback=None
393
+ )
394
+
395
+ agent_logger.log("ensemble_monitor", "info", f"Cleaned forensic images types: {[type(img) for img in cleaned_forensics_images]}")
396
+ for i, res_dict in enumerate(results):
397
+ for key in ["AI Score", "Real Score"]:
398
+ value = res_dict.get(key)
399
+ if isinstance(value, np.float32):
400
+ res_dict[key] = float(value)
401
+ agent_logger.log("ensemble_monitor", "info", f"Converted {key} for result {i} from numpy.float32 to float.")
402
+ json_results = json.dumps(results, cls=NumpyEncoder)
403
+ # Read log file contents for each agent
404
+ def read_log_file(path):
405
+ try:
406
+ with open(path, "r") as f:
407
+ return f.read()
408
+ except Exception:
409
+ return ""
410
+
411
+ yield (
412
+ img_pil,
413
+ cleaned_forensics_images,
414
+ table_rows,
415
+ json_results,
416
+ consensus_html,
417
+ read_log_file(AGENT_LOG_FILES["context_intelligence"]),
418
+ read_log_file(AGENT_LOG_FILES["ensemble_monitor"]),
419
+ read_log_file(AGENT_LOG_FILES["weight_optimization"]),
420
+ read_log_file(AGENT_LOG_FILES["system_health"]),
421
+ read_log_file(AGENT_LOG_FILES["forensic_anomaly_detection"])
422
+ )
423
+
424
+ with gr.Blocks() as detection_model_eval_playground:
425
+ gr.Markdown("# Multi-Model Ensemble + Agentic Coordinated Deepfake Detection (Paper in Progress)")
426
+ gr.Markdown("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.")
427
+ with gr.Row():
428
+ with gr.Column():
429
+ img_input = gr.Image(label="Upload Image to Analyze", sources=['upload', 'webcam'], type='filepath')
430
+ confidence_slider = gr.Slider(0.0, 1.0, value=0.8, step=0.05, label="Confidence Threshold", visible=False)
431
+ rotate_slider = gr.Slider(0, 45, value=0, step=1, label="Rotate Degrees", visible=False)
432
+ noise_slider = gr.Slider(0, 50, value=0, step=1, label="Noise Level", visible=False)
433
+ sharpen_slider = gr.Slider(0, 50, value=0, step=1, label="Sharpen Strength", visible=False)
434
+ predict_btn = gr.Button("Run Prediction")
435
+ with gr.Column():
436
+ processed_img = gr.Image(label="Processed Image", visible=False)
437
+
438
+ predictions_df = gr.Dataframe(
439
+ label="Model Predictions",
440
+ headers=["Model", "By", "AI", "Real", "Label"],
441
+ datatype=["str", "str", "number", "number", "str"],
442
+ show_label=False,
443
+ row_count=(8, "dynamic")
444
+
445
+ )
446
+ gallery = gr.Gallery(label="Post Processed Images", visible=True, columns=[4], rows=[2], container=False, height="auto", object_fit="contain", elem_id="post-gallery")
447
+ raw_json = gr.JSON(label="Raw Model Results", visible=False)
448
+ consensus_md = gr.Markdown(label="Consensus", value="")
449
+ with gr.Accordion("Agent Logs", open=True, elem_id="agent-logs-accordion"):
450
+ with gr.Row():
451
+ with gr.Column():
452
+ context_intelligence_log = Log(label="Context Log", dark=True, xterm_font_size=12, log_file=AGENT_LOG_FILES["context_intelligence"], tail=40)
453
+ ensemble_monitor_log = Log(label="Ensemble Monitor Log", dark=True, xterm_font_size=12, log_file=AGENT_LOG_FILES["ensemble_monitor"], tail=40)
454
+ with gr.Column():
455
+ weight_optimization_log = Log(label="Weight Optimization Log", dark=True, xterm_font_size=12, log_file=AGENT_LOG_FILES["weight_optimization"], tail=40)
456
+ forensic_log = Log(label="Forensic Anomaly Log", dark=True, xterm_font_size=12, log_file=AGENT_LOG_FILES["forensic_anomaly_detection"], tail=40)
457
+ system_health_log = Log(label="System Health Log", dark=True, xterm_font_size=12, log_file=AGENT_LOG_FILES["system_health"], visible=False, tail=40)
458
+
459
+ predict_btn.click(
460
+ full_prediction,
461
+ inputs=[img_input, confidence_slider, rotate_slider, noise_slider, sharpen_slider],
462
+ outputs=[
463
+ processed_img,
464
+ gallery,
465
+ predictions_df,
466
+ raw_json,
467
+ consensus_md,
468
+ context_intelligence_log,
469
+ ensemble_monitor_log,
470
+ weight_optimization_log,
471
+ system_health_log,
472
+ forensic_log
473
+ ]
474
+ )
475
+ # def echo_headers(x, request: gr.Request):
476
+ # print(dict(request.headers))
477
+ # return str(dict(request.headers))
478
+
479
+
480
+ def predict(img):
481
+ """
482
+ Predicts whether an image is AI-generated or real using the SOTA Community Forensics model.
483
+
484
+ Args:
485
+ img (str): Path to the input image file to analyze.
486
+
487
+ Returns:
488
+ dict: A dictionary containing:
489
+ - 'Fake Probability' (float): Probability score between 0 and 1 indicating likelihood of being AI-generated
490
+ - 'Result Description' (str): Human-readable description of the prediction result
491
+
492
+ Example:
493
+ >>> result = predict("path/to/image.jpg")
494
+ >>> print(result)
495
+ {'Fake Probability': 0.002, 'Result Description': 'The image is likely real.'}
496
+ """
497
+ client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
498
+ client.view_api()
499
+ result = client.predict(
500
+ handle_file(img),
501
+ api_name="/simple_predict"
502
+ )
503
+ return str(result)
504
+ community_forensics_preview = gr.Interface(
505
+ fn=predict,
506
+ inputs=gr.Image(type="filepath"),
507
+ outputs=gr.HTML(), # or gr.Markdown() if it's just text
508
+ title="Quick and simple prediction by our strongest model.",
509
+ description="No ensemble, no context, no agents, just a quick and simple prediction by our strongest model.",
510
+ api_name="predict"
511
+ )
512
+
513
+ # leaderboard = gr.Interface(
514
+ # fn=lambda: "# AI Generated / Deepfake Detection Models Leaderboard: Soon™",
515
+ # inputs=None,
516
+ # outputs=gr.Markdown(),
517
+ # title="Leaderboard",
518
+ # api_name="leaderboard"
519
+ # )
520
+
521
+ def simple_prediction(img):
522
+ """
523
+ Quick and simple deepfake or real image prediction by the strongest open-source model on the hub.
524
+
525
+ Args:
526
+ img (str): The input image to analyze, provided as a file path.
527
+
528
+ Returns:
529
+ str: The prediction result stringified from dict. Example: `{'Fake Probability': 0.002, 'Result Description': 'The image is likely real.'}`
530
+ """
531
+ client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
532
+ client.view_api()
533
+ client.predict(
534
+ handle_file(img),
535
+ api_name="simple_predict"
536
+ )
537
+ simple_predict_interface = gr.Interface(
538
+ fn=simple_prediction,
539
+ inputs=gr.Image(type="filepath"),
540
+ outputs=gr.Text(),
541
+ title="Quick and simple prediction by our strongest model.",
542
+ description="No ensemble, no context, no agents, just a quick and simple prediction by our strongest model.",
543
+ api_name="simple_predict"
544
+ )
545
+
546
+ noise_estimation_interface = gr.Interface(
547
+ fn=noise_estimation,
548
+ inputs=[gr.Image(type="pil"), gr.Slider(1, 32, value=8, step=1, label="Block Size")],
549
+ outputs=gr.Image(type="pil"),
550
+ title="Wavelet-Based Noise Analysis",
551
+ 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.",
552
+ api_name="tool_waveletnoise"
553
+ )
554
+
555
+ bit_plane_interface = gr.Interface(
556
+ fn=bit_plane_extractor,
557
+ inputs=[
558
+ gr.Image(type="pil"),
559
+ gr.Dropdown(["Luminance", "Red", "Green", "Blue", "RGB Norm"], label="Channel", value="Luminance"),
560
+ gr.Slider(0, 7, value=0, step=1, label="Bit Plane"),
561
+ gr.Dropdown(["Disabled", "Median", "Gaussian"], label="Filter", value="Disabled")
562
+ ],
563
+ outputs=gr.Image(type="pil"),
564
+ title="Bit Plane Analysis",
565
+ 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.",
566
+ api_name="tool_bitplane"
567
+ )
568
+
569
+ ela_interface = gr.Interface(
570
+ fn=ELA,
571
+ inputs=[
572
+ gr.Image(type="pil", label="Input Image"),
573
+ gr.Slider(1, 100, value=75, step=1, label="JPEG Quality"),
574
+ gr.Slider(1, 100, value=50, step=1, label="Output Scale (Multiplicative Gain)"),
575
+ gr.Slider(0, 100, value=20, step=1, label="Output Contrast (Tonality Compression)"),
576
+ gr.Checkbox(value=False, label="Use Linear Difference"),
577
+ gr.Checkbox(value=False, label="Grayscale Output")
578
+ ],
579
+ outputs=gr.Image(type="pil"),
580
+ title="Error Level Analysis (ELA)",
581
+ 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.",
582
+ api_name="tool_ela"
583
+ )
584
+
585
+ gradient_processing_interface = gr.Interface(
586
+ fn=gradient_processing,
587
+ inputs=[
588
+ gr.Image(type="pil", label="Input Image"),
589
+ gr.Slider(0, 100, value=90, step=1, label="Intensity"),
590
+ gr.Dropdown(["Abs", "None", "Flat", "Norm"], label="Blue Mode", value="Abs"),
591
+ gr.Checkbox(value=False, label="Invert Gradients"),
592
+ gr.Checkbox(value=False, label="Equalize Histogram")
593
+ ],
594
+ outputs=gr.Image(type="pil"),
595
+ title="Gradient Processing",
596
+ description="Applies gradient filters to an image to enhance edges and transitions, which can reveal inconsistencies due to manipulation.",
597
+ api_name="tool_gradient_processing"
598
+ )
599
+
600
+ minmax_processing_interface = gr.Interface(
601
+ fn=minmax_process,
602
+ inputs=[
603
+ gr.Image(type="pil", label="Input Image"),
604
+ gr.Radio([0, 1, 2, 3, 4], label="Channel (0:Grayscale, 1:Blue, 2:Green, 3:Red, 4:RGB Norm)", value=4),
605
+ gr.Slider(0, 10, value=2, step=1, label="Radius")
606
+ ],
607
+ outputs=gr.Image(type="pil"),
608
+ title="MinMax Processing",
609
+ description="Analyzes local pixel value deviations to detect subtle changes in image data, often indicative of digital forgeries.",
610
+ api_name="tool_minmax_processing"
611
+ )
612
+
613
+ # augmentation_tool_interface = gr.Interface(
614
+ # fn=augment_image,
615
+ # inputs=[
616
+ # gr.Image(label="Upload Image to Augment", sources=['upload', 'webcam'], type='pil'),
617
+ # gr.CheckboxGroup(["rotate", "add_noise", "sharpen"], label="Augmentation Methods"),
618
+ # gr.Slider(0, 360, value=0, step=1, label="Rotate Degrees", visible=True),
619
+ # gr.Slider(0, 100, value=0, step=1, label="Noise Level", visible=True),
620
+ # gr.Slider(0, 200, value=1, step=1, label="Sharpen Strength", visible=True)
621
+ # ],
622
+ # outputs=gr.Image(label="Augmented Image", type='pil'),
623
+ # title="Image Augmentation Tool",
624
+ # description="Apply various augmentation techniques to your image.",
625
+ # api_name="augment_image"
626
+ # )
627
+
628
+ # def get_captured_logs():
629
+ # # Retrieve all logs from the queue and clear it
630
+ # logs = list(log_queue)
631
+ # log_queue.clear() # Clear the queue after retrieving
632
+ # return "\n".join(logs)
633
+
634
+ demo = detection_model_eval_playground
635
+
636
+ # demo = gr.TabbedInterface(
637
+ # [
638
+ # detection_model_eval_playground,
639
+ # community_forensics_preview,
640
+ # noise_estimation_interface,
641
+ # bit_plane_interface,
642
+ # ela_interface,
643
+ # gradient_processing_interface,
644
+ # minmax_processing_interface,
645
+ # # gr.Textbox(label="Agent Logs", interactive=False, lines=5, max_lines=20, autoscroll=True) # New textbox for logs
646
+ # ],
647
+ # [
648
+ # "Run Ensemble Prediction",
649
+ # "Open-Source SOTA Model",
650
+ # "Wavelet Blocking Noise Estimation",
651
+ # "Bit Plane Values",
652
+ # "Error Level Analysis (ELA)",
653
+ # "Gradient Processing",
654
+ # "MinMax Processing",
655
+ # # "Agent Logs" # New tab title
656
+ # ],
657
+ # title="Deepfake Detection & Forensics Tools",
658
+ # theme=None,
659
+
660
+ # )
661
+
662
+
663
+ footerMD = """
664
+ ## ⚠️ ENSEMBLE TEAM IN TRAINING ⚠️ \n\n
665
+
666
+ **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.**
667
+ """
668
+ footer = gr.Markdown(footerMD, elem_classes="footer")
669
+
670
+ with gr.Blocks() as app:
671
+ demo.render()
672
+
673
+ footer.render()
674
+
675
+
676
+ app.queue(max_size=10, default_concurrency_limit=1).launch()