LPX commited on
Commit
63aad13
·
1 Parent(s): 31239ef

test: refactored for mcp specs

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. app_test.py +537 -0
README.md CHANGED
@@ -6,7 +6,7 @@ colorFrom: yellow
6
  colorTo: yellow
7
  sdk: gradio
8
  sdk_version: 5.33.0
9
- app_file: app_mcp.py
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_test.py
10
  pinned: true
11
  models:
12
  - aiwithoutborders-xyz/OpenSight-CommunityForensics-Deepfake-ViT
app_test.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_client import Client, handle_file
3
+ from PIL import Image
4
+ import numpy as np
5
+ import os
6
+ import time
7
+ import logging
8
+
9
+ # Assuming these are available from your utils and agents directories
10
+ # You might need to adjust paths or copy these functions/classes if they are not directly importable.
11
+ from utils.utils import softmax, augment_image
12
+ from utils.gradient import gradient_processing
13
+ from utils.minmax import minmax_process
14
+ from utils.ela import ELA
15
+ from utils.wavelet import wavelet_blocking_noise_estimation
16
+ from utils.bitplane import bit_plane_extractor
17
+ from utils.hf_logger import log_inference_data
18
+ from agents.ensemble_team import EnsembleMonitorAgent, WeightOptimizationAgent, SystemHealthAgent
19
+ from agents.smart_agents import ContextualIntelligenceAgent, ForensicAnomalyDetectionAgent
20
+ from forensics.registry import register_model, MODEL_REGISTRY, ModelEntry
21
+ from agents.ensemble_weights import ModelWeightManager
22
+ from transformers import pipeline, AutoImageProcessor, SwinForImageClassification, Swinv2ForImageClassification, AutoFeatureExtractor, AutoModelForImageClassification
23
+ from torchvision import transforms
24
+ import torch
25
+ import json
26
+ from huggingface_hub import CommitScheduler
27
+ from dotenv import load_dotenv
28
+
29
+ # Configure logging
30
+ logging.basicConfig(level=logging.INFO)
31
+ logger = logging.getLogger(__name__)
32
+ os.environ['HF_HUB_CACHE'] = './models'
33
+
34
+ LOCAL_LOG_DIR = "./hf_inference_logs"
35
+ HF_DATASET_NAME="degentic_rd0"
36
+ load_dotenv()
37
+
38
+ # Custom JSON Encoder to handle numpy types
39
+ class NumpyEncoder(json.JSONEncoder):
40
+ def default(self, obj):
41
+ if isinstance(obj, np.float32):
42
+ return float(obj)
43
+ return json.JSONEncoder.default(self, obj)
44
+
45
+ # Ensure using GPU if available
46
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
47
+
48
+ # Model paths and class names (copied from app_mcp.py)
49
+ MODEL_PATHS = {
50
+ "model_1": "haywoodsloan/ai-image-detector-deploy",
51
+ "model_2": "Heem2/AI-vs-Real-Image-Detection",
52
+ "model_3": "Organika/sdxl-detector",
53
+ "model_4": "cmckinle/sdxl-flux-detector_v1.1",
54
+ "model_5": "prithivMLmods/Deep-Fake-Detector-v2-Model",
55
+ "model_6": "ideepankarsharma2003/AI_ImageClassification_MidjourneyV6_SDXL",
56
+ "model_7": "date3k2/vit-real-fake-classification-v4"
57
+ }
58
+
59
+ CLASS_NAMES = {
60
+ "model_1": ['artificial', 'real'],
61
+ "model_2": ['AI Image', 'Real Image'],
62
+ "model_3": ['AI', 'Real'],
63
+ "model_4": ['AI', 'Real'],
64
+ "model_5": ['Realism', 'Deepfake'],
65
+ "model_6": ['ai_gen', 'human'],
66
+ "model_7": ['Fake', 'Real'],
67
+ }
68
+
69
+ def preprocess_resize_256(image):
70
+ if image.mode != 'RGB':
71
+ image = image.convert('RGB')
72
+ return transforms.Resize((256, 256))(image)
73
+
74
+ def preprocess_resize_224(image):
75
+ if image.mode != 'RGB':
76
+ image = image.convert('RGB')
77
+ return transforms.Resize((224, 224))(image)
78
+
79
+ def postprocess_pipeline(prediction, class_names):
80
+ # Assumes HuggingFace pipeline output
81
+ return {pred['label']: pred['score'] for pred in prediction}
82
+
83
+ def postprocess_logits(outputs, class_names):
84
+ # Assumes model output with logits
85
+ logits = outputs.logits.cpu().numpy()[0]
86
+ probabilities = softmax(logits)
87
+ return {class_names[i]: probabilities[i] for i in range(len(class_names))}
88
+
89
+ def register_model_with_metadata(model_id, model, preprocess, postprocess, class_names, display_name, contributor, model_path):
90
+ entry = ModelEntry(model, preprocess, postprocess, class_names)
91
+ entry.display_name = display_name
92
+ entry.contributor = contributor
93
+ entry.model_path = model_path
94
+ MODEL_REGISTRY[model_id] = entry
95
+
96
+ # Load and register models (copied from app_mcp.py)
97
+ image_processor_1 = AutoImageProcessor.from_pretrained(MODEL_PATHS["model_1"], use_fast=True)
98
+ model_1 = Swinv2ForImageClassification.from_pretrained(MODEL_PATHS["model_1"]).to(device)
99
+ clf_1 = pipeline(model=model_1, task="image-classification", image_processor=image_processor_1, device=device)
100
+ register_model_with_metadata(
101
+ "model_1", clf_1, preprocess_resize_256, postprocess_pipeline, CLASS_NAMES["model_1"],
102
+ display_name="SwinV2 Based", contributor="haywoodsloan", model_path=MODEL_PATHS["model_1"]
103
+ )
104
+
105
+ clf_2 = pipeline("image-classification", model=MODEL_PATHS["model_2"], device=device)
106
+ register_model_with_metadata(
107
+ "model_2", clf_2, preprocess_resize_224, postprocess_pipeline, CLASS_NAMES["model_2"],
108
+ display_name="ViT Based", contributor="Heem2", model_path=MODEL_PATHS["model_2"]
109
+ )
110
+
111
+ feature_extractor_3 = AutoFeatureExtractor.from_pretrained(MODEL_PATHS["model_3"], device=device)
112
+ model_3 = AutoModelForImageClassification.from_pretrained(MODEL_PATHS["model_3"]).to(device)
113
+ def preprocess_256(image):
114
+ if image.mode != 'RGB':
115
+ image = image.convert('RGB')
116
+ return transforms.Resize((256, 256))(image)
117
+ def postprocess_logits_model3(outputs, class_names):
118
+ logits = outputs.logits.cpu().numpy()[0]
119
+ probabilities = softmax(logits)
120
+ return {class_names[i]: probabilities[i] for i in range(len(class_names))}
121
+ def model3_infer(image):
122
+ inputs = feature_extractor_3(image, return_tensors="pt").to(device)
123
+ with torch.no_grad():
124
+ outputs = model_3(**inputs)
125
+ return outputs
126
+ register_model_with_metadata(
127
+ "model_3", model3_infer, preprocess_256, postprocess_logits_model3, CLASS_NAMES["model_3"],
128
+ display_name="SDXL Dataset", contributor="Organika", model_path=MODEL_PATHS["model_3"]
129
+ )
130
+
131
+ feature_extractor_4 = AutoFeatureExtractor.from_pretrained(MODEL_PATHS["model_4"], device=device)
132
+ model_4 = AutoModelForImageClassification.from_pretrained(MODEL_PATHS["model_4"]).to(device)
133
+ def model4_infer(image):
134
+ inputs = feature_extractor_4(image, return_tensors="pt").to(device)
135
+ with torch.no_grad():
136
+ outputs = model_4(**inputs)
137
+ return outputs
138
+ def postprocess_logits_model4(outputs, class_names):
139
+ logits = outputs.logits.cpu().numpy()[0]
140
+ probabilities = softmax(logits)
141
+ return {class_names[i]: probabilities[i] for i in range(len(class_names))}
142
+ register_model_with_metadata(
143
+ "model_4", model4_infer, preprocess_256, postprocess_logits_model4, CLASS_NAMES["model_4"],
144
+ display_name="SDXL + FLUX", contributor="cmckinle", model_path=MODEL_PATHS["model_4"]
145
+ )
146
+
147
+ clf_5 = pipeline("image-classification", model=MODEL_PATHS["model_5"], device=device)
148
+ register_model_with_metadata(
149
+ "model_5", clf_5, preprocess_resize_224, postprocess_pipeline, CLASS_NAMES["model_5"],
150
+ display_name="Vit Based", contributor="prithivMLmods", model_path=MODEL_PATHS["model_5"]
151
+ )
152
+
153
+ image_processor_6 = AutoImageProcessor.from_pretrained(MODEL_PATHS["model_6"], use_fast=True)
154
+ model_6 = SwinForImageClassification.from_pretrained(MODEL_PATHS["model_6"]).to(device)
155
+ clf_6 = pipeline(model=model_6, task="image-classification", image_processor=image_processor_6, device=device)
156
+ register_model_with_metadata(
157
+ "model_6", clf_6, preprocess_resize_224, postprocess_pipeline, CLASS_NAMES["model_6"],
158
+ display_name="Swin, Midj + SDXL", contributor="ideepankarsharma2003", model_path=MODEL_PATHS["model_6"]
159
+ )
160
+
161
+ image_processor_7 = AutoImageProcessor.from_pretrained(MODEL_PATHS["model_7"], use_fast=True)
162
+ model_7 = AutoModelForImageClassification.from_pretrained(MODEL_PATHS["model_7"]).to(device)
163
+ clf_7 = pipeline(model=model_7, task="image-classification", image_processor=image_processor_7, device=device)
164
+ register_model_with_metadata(
165
+ "model_7", clf_7, preprocess_resize_224, postprocess_pipeline, CLASS_NAMES["model_7"],
166
+ display_name="ViT", contributor="temp", model_path=MODEL_PATHS["model_7"]
167
+ )
168
+
169
+ def infer(image: Image.Image, model_id: str, confidence_threshold: float = 0.75) -> dict:
170
+ entry = MODEL_REGISTRY[model_id]
171
+ img = entry.preprocess(image)
172
+ try:
173
+ result = entry.model(img)
174
+ scores = entry.postprocess(result, entry.class_names)
175
+ ai_score = float(scores.get(entry.class_names[0], 0.0))
176
+ real_score = float(scores.get(entry.class_names[1], 0.0))
177
+ label = "AI" if ai_score >= confidence_threshold else ("REAL" if real_score >= confidence_threshold else "UNCERTAIN")
178
+ return {
179
+ "Model": entry.display_name,
180
+ "Contributor": entry.contributor,
181
+ "HF Model Path": entry.model_path,
182
+ "AI Score": ai_score,
183
+ "Real Score": real_score,
184
+ "Label": label
185
+ }
186
+ except Exception as e:
187
+ return {
188
+ "Model": entry.display_name,
189
+ "Contributor": entry.contributor,
190
+ "HF Model Path": entry.model_path,
191
+ "AI Score": 0.0,
192
+ "Real Score": 0.0,
193
+ "Label": f"Error: {str(e)}"
194
+ }
195
+
196
+ def predict_with_ensemble(img, confidence_threshold, augment_methods, rotate_degrees, noise_level, sharpen_strength):
197
+ if not isinstance(img, Image.Image):
198
+ try:
199
+ img = Image.fromarray(img)
200
+ except Exception as e:
201
+ logger.error(f"Error converting input image to PIL: {e}")
202
+ raise ValueError("Input image could not be converted to PIL Image.")
203
+
204
+ monitor_agent = EnsembleMonitorAgent()
205
+ weight_manager = ModelWeightManager()
206
+ optimization_agent = WeightOptimizationAgent(weight_manager)
207
+ health_agent = SystemHealthAgent()
208
+ context_agent = ContextualIntelligenceAgent()
209
+ anomaly_agent = ForensicAnomalyDetectionAgent()
210
+
211
+ health_agent.monitor_system_health()
212
+
213
+ if augment_methods:
214
+ img_pil, _ = augment_image(img, augment_methods, rotate_degrees, noise_level, sharpen_strength)
215
+ else:
216
+ img_pil = img
217
+ img_np_og = np.array(img) # Convert PIL Image to NumPy array
218
+
219
+ model_predictions_raw = {}
220
+ confidence_scores = {}
221
+ results = []
222
+
223
+ for model_id in MODEL_REGISTRY:
224
+ model_start = time.time()
225
+ result = infer(img_pil, model_id, confidence_threshold)
226
+ model_end = time.time()
227
+
228
+ monitor_agent.monitor_prediction(
229
+ model_id,
230
+ result["Label"],
231
+ max(result.get("AI Score", 0.0), result.get("Real Score", 0.0)),
232
+ model_end - model_start
233
+ )
234
+
235
+ model_predictions_raw[model_id] = result
236
+ confidence_scores[model_id] = max(result.get("AI Score", 0.0), result.get("Real Score", 0.0))
237
+ results.append(result)
238
+
239
+ image_data_for_context = {
240
+ "width": img.width,
241
+ "height": img.height,
242
+ "mode": img.mode,
243
+ }
244
+ detected_context_tags = context_agent.infer_context_tags(image_data_for_context, model_predictions_raw)
245
+ logger.info(f"Detected context tags: {detected_context_tags}")
246
+
247
+ adjusted_weights = weight_manager.adjust_weights(model_predictions_raw, confidence_scores, context_tags=detected_context_tags)
248
+
249
+ weighted_predictions = {
250
+ "AI": 0.0,
251
+ "REAL": 0.0,
252
+ "UNCERTAIN": 0.0
253
+ }
254
+
255
+ for model_id, prediction in model_predictions_raw.items():
256
+ prediction_label = prediction.get("Label")
257
+ if prediction_label in weighted_predictions:
258
+ weighted_predictions[prediction_label] += adjusted_weights[model_id]
259
+ else:
260
+ logger.warning(f"Unexpected prediction label '{prediction_label}' from model '{model_id}'. Skipping its weight in consensus.")
261
+
262
+ final_prediction_label = "UNCERTAIN"
263
+ if weighted_predictions["AI"] > weighted_predictions["REAL"] and weighted_predictions["AI"] > weighted_predictions["UNCERTAIN"]:
264
+ final_prediction_label = "AI"
265
+ elif weighted_predictions["REAL"] > weighted_predictions["AI"] and weighted_predictions["REAL"] > weighted_predictions["UNCERTAIN"]:
266
+ final_prediction_label = "REAL"
267
+
268
+ optimization_agent.analyze_performance(final_prediction_label, None)
269
+
270
+ gradient_image = gradient_processing(img_np_og)
271
+ gradient_image2 = gradient_processing(img_np_og, intensity=45, equalize=True)
272
+
273
+ minmax_image = minmax_process(img_np_og)
274
+ minmax_image2 = minmax_process(img_np_og, radius=6)
275
+ bitplane_image = bit_plane_extractor(img_pil)
276
+
277
+ ela1 = ELA(img_np_og, quality=75, scale=50, contrast=20, linear=False, grayscale=True)
278
+ ela2 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=True)
279
+ ela3 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=False)
280
+
281
+ forensics_images = [img_pil, ela1, ela2, ela3, gradient_image, gradient_image2, minmax_image, minmax_image2, bitplane_image]
282
+
283
+ forensic_output_descriptions = [
284
+ f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
285
+ "ELA analysis (Pass 1): Grayscale error map, quality 75.",
286
+ "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
287
+ "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
288
+ "Gradient processing: Highlights edges and transitions.",
289
+ "Gradient processing: Int=45, Equalize=True",
290
+ "MinMax processing: Deviations in local pixel values.",
291
+ "MinMax processing (Radius=6): Deviations in local pixel values.",
292
+ "Bit Plane extractor: Visualization of individual bit planes from different color channels."
293
+ ]
294
+ anomaly_detection_results = anomaly_agent.analyze_forensic_outputs(forensic_output_descriptions)
295
+ logger.info(f"Forensic anomaly detection: {anomaly_detection_results['summary']}")
296
+
297
+ table_rows = [[
298
+ r.get("Model", ""),
299
+ r.get("Contributor", ""),
300
+ r.get("AI Score", 0.0) if r.get("AI Score") is not None else 0.0,
301
+ r.get("Real Score", 0.0) if r.get("Real Score") is not None else 0.0,
302
+ r.get("Label", "Error")
303
+ ] for r in results]
304
+
305
+ logger.info(f"Type of table_rows: {type(table_rows)}")
306
+ for i, row in enumerate(table_rows):
307
+ logger.info(f"Row {i} types: {[type(item) for item in row]}")
308
+
309
+ consensus_html = f"<b><span style='color:{'red' if final_prediction_label == 'AI' else ('green' if final_prediction_label == 'REAL' else 'orange')}'>{final_prediction_label}</span></b>"
310
+
311
+ inference_params = {
312
+ "confidence_threshold": confidence_threshold,
313
+ "augment_methods": augment_methods,
314
+ "rotate_degrees": rotate_degrees,
315
+ "noise_level": noise_level,
316
+ "sharpen_strength": sharpen_strength,
317
+ "detected_context_tags": detected_context_tags
318
+ }
319
+
320
+ ensemble_output_data = {
321
+ "final_prediction_label": final_prediction_label,
322
+ "weighted_predictions": weighted_predictions,
323
+ "adjusted_weights": adjusted_weights
324
+ }
325
+
326
+ agent_monitoring_data_log = {
327
+ "ensemble_monitor": {
328
+ "alerts": monitor_agent.alerts,
329
+ "performance_metrics": monitor_agent.performance_metrics
330
+ },
331
+ "weight_optimization": {
332
+ "prediction_history_length": len(optimization_agent.prediction_history),
333
+ },
334
+ "system_health": {
335
+ "memory_usage": health_agent.health_metrics["memory_usage"],
336
+ "gpu_utilization": health_agent.health_metrics["gpu_utilization"]
337
+ },
338
+ "context_intelligence": {
339
+ "detected_context_tags": detected_context_tags
340
+ },
341
+ "forensic_anomaly_detection": anomaly_detection_results
342
+ }
343
+
344
+ log_inference_data(
345
+ original_image=img,
346
+ inference_params=inference_params,
347
+ model_predictions=results,
348
+ ensemble_output=ensemble_output_data,
349
+ forensic_images=forensics_images,
350
+ agent_monitoring_data=agent_monitoring_data_log,
351
+ human_feedback=None
352
+ )
353
+
354
+ cleaned_forensics_images = []
355
+ for f_img in forensics_images:
356
+ if isinstance(f_img, Image.Image):
357
+ cleaned_forensics_images.append(f_img)
358
+ elif isinstance(f_img, np.ndarray):
359
+ try:
360
+ cleaned_forensics_images.append(Image.fromarray(f_img))
361
+ except Exception as e:
362
+ logger.warning(f"Could not convert numpy array to PIL Image for gallery: {e}")
363
+ else:
364
+ logger.warning(f"Unexpected type in forensic_images: {type(f_img)}. Skipping.")
365
+
366
+ logger.info(f"Cleaned forensic images types: {[type(img) for img in cleaned_forensics_images]}")
367
+
368
+ for i, res_dict in enumerate(results):
369
+ for key in ["AI Score", "Real Score"]:
370
+ value = res_dict.get(key)
371
+ if isinstance(value, np.float32):
372
+ res_dict[key] = float(value)
373
+ logger.info(f"Converted {key} for result {i} from numpy.float32 to float.")
374
+
375
+ json_results = json.dumps(results, cls=NumpyEncoder)
376
+
377
+ return img_pil, cleaned_forensics_images, table_rows, json_results, consensus_html
378
+
379
+ def simple_prediction(img):
380
+ client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
381
+ result = client.predict(
382
+ input_image=handle_file(img),
383
+ api_name="/simple_predict"
384
+ )
385
+ return result
386
+
387
+
388
+ detection_model_eval_playground = gr.Interface(
389
+ fn=predict_with_ensemble,
390
+ inputs=[
391
+ gr.Image(label="Upload Image to Analyze", sources=['upload', 'webcam'], type='pil'),
392
+ gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Confidence Threshold"),
393
+ gr.CheckboxGroup(["rotate", "add_noise", "sharpen"], label="Augmentation Methods"),
394
+ gr.Slider(0, 45, value=0, step=1, label="Rotate Degrees", visible=False),
395
+ gr.Slider(0, 50, value=0, step=1, label="Noise Level", visible=False),
396
+ gr.Slider(0, 50, value=0, step=1, label="Sharpen Strength", visible=False)
397
+ ],
398
+ outputs=[
399
+ gr.Image(label="Processed Image", visible=False),
400
+ gr.Gallery(label="Post Processed Images", visible=True, columns=[4], rows=[2], container=False, height="auto", object_fit="contain", elem_id="post-gallery"),
401
+ gr.Dataframe(
402
+ label="Model Predictions",
403
+ headers=["Model", "Contributor", "AI Score", "Real Score", "Label"],
404
+ datatype=["str", "str", "number", "number", "str"]
405
+ ),
406
+ gr.JSON(label="Raw Model Results", visible=False),
407
+ gr.Markdown(label="Consensus", value="")
408
+ ],
409
+ title="Open Source Detection Models Found on the Hub",
410
+ description="Space will be upgraded shortly; inference on all 6 models should take about 1.2~ seconds once we're back on CUDA. The Community Forensics mother of all detection models is now available for inference, head to the middle tab above this. Lots of exciting things coming up, stay tuned!",
411
+ api_name="predict"
412
+ )
413
+
414
+ community_forensics_preview = gr.Interface(
415
+ fn=lambda: gr.load("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview", src="spaces"),
416
+ inputs=None,
417
+ outputs=gr.HTML(), # or gr.Markdown() if it's just text
418
+ title="Community Forensics Preview",
419
+ description="Community Forensics Preview coming soon!",
420
+ api_name="community_forensics"
421
+ )
422
+
423
+ leaderboard = gr.Interface(
424
+ fn=lambda: "# AI Generated / Deepfake Detection Models Leaderboard: Soon™",
425
+ inputs=None,
426
+ outputs=gr.Markdown(),
427
+ title="Leaderboard",
428
+ api_name="leaderboard"
429
+ )
430
+
431
+ simple_predict_interface = gr.Interface(
432
+ fn=simple_prediction,
433
+ inputs=gr.Image(type="filepath"),
434
+ outputs=gr.Text(),
435
+ title="Simple and Fast Prediction",
436
+ description="",
437
+ api_name="simple_predict"
438
+ )
439
+
440
+ wavelet_noise_estimation = gr.Interface(
441
+ fn=wavelet_blocking_noise_estimation,
442
+ inputs=[gr.Image(type="pil"), gr.Slider(1, 32, value=8, step=1, label="Block Size")],
443
+ outputs=gr.Image(type="pil"),
444
+ title="Wavelet-Based Noise Analysis",
445
+ 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.",
446
+ api_name="tool_waveletnoise"
447
+ )
448
+
449
+ bit_plane_interface = gr.Interface(
450
+ fn=bit_plane_extractor,
451
+ inputs=[
452
+ gr.Image(type="pil"),
453
+ gr.Dropdown(["Luminance", "Red", "Green", "Blue", "RGB Norm"], label="Channel", value="Luminance"),
454
+ gr.Slider(0, 7, value=0, step=1, label="Bit Plane"),
455
+ gr.Dropdown(["Disabled", "Median", "Gaussian"], label="Filter", value="Disabled")
456
+ ],
457
+ outputs=gr.Image(type="pil"),
458
+ title="Bit Plane Analysis",
459
+ 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.",
460
+ api_name="tool_bitplane"
461
+ )
462
+
463
+ ela_interface = gr.Interface(
464
+ fn=ELA,
465
+ inputs=[
466
+ gr.Image(type="pil", label="Input Image"),
467
+ gr.Slider(1, 100, value=75, step=1, label="JPEG Quality"),
468
+ gr.Slider(1, 100, value=50, step=1, label="Output Scale (Multiplicative Gain)"),
469
+ gr.Slider(0, 100, value=20, step=1, label="Output Contrast (Tonality Compression)"),
470
+ gr.Checkbox(value=False, label="Use Linear Difference"),
471
+ gr.Checkbox(value=False, label="Grayscale Output")
472
+ ],
473
+ outputs=gr.Image(type="pil"),
474
+ title="Error Level Analysis (ELA)",
475
+ 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.",
476
+ api_name="tool_ela"
477
+ )
478
+
479
+ gradient_processing_interface = gr.Interface(
480
+ fn=gradient_processing,
481
+ inputs=[
482
+ gr.Image(type="pil", label="Input Image"),
483
+ gr.Slider(0, 100, value=90, step=1, label="Intensity"),
484
+ gr.Dropdown(["Abs", "None", "Flat", "Norm"], label="Blue Mode", value="Abs"),
485
+ gr.Checkbox(value=False, label="Invert Gradients"),
486
+ gr.Checkbox(value=False, label="Equalize Histogram")
487
+ ],
488
+ outputs=gr.Image(type="pil"),
489
+ title="Gradient Processing",
490
+ description="Applies gradient filters to an image to enhance edges and transitions, which can reveal inconsistencies due to manipulation.",
491
+ api_name="tool_gradient_processing"
492
+ )
493
+
494
+ minmax_processing_interface = gr.Interface(
495
+ fn=minmax_process,
496
+ inputs=[
497
+ gr.Image(type="pil", label="Input Image"),
498
+ gr.Radio([0, 1, 2, 3, 4], label="Channel (0:Grayscale, 1:Blue, 2:Green, 3:Red, 4:RGB Norm)", value=4),
499
+ gr.Slider(0, 10, value=2, step=1, label="Radius")
500
+ ],
501
+ outputs=gr.Image(type="pil"),
502
+ title="MinMax Processing",
503
+ description="Analyzes local pixel value deviations to detect subtle changes in image data, often indicative of digital forgeries.",
504
+ api_name="tool_minmax_processing"
505
+ )
506
+
507
+ demo = gr.TabbedInterface(
508
+ [
509
+ detection_model_eval_playground,
510
+ simple_predict_interface,
511
+ wavelet_noise_estimation,
512
+ bit_plane_interface,
513
+ ela_interface,
514
+ gradient_processing_interface,
515
+ minmax_processing_interface
516
+ ],
517
+ [
518
+ "Run Ensemble Prediction",
519
+ "Simple Predict",
520
+ "Wavelet Blocking Noise Estimation",
521
+ "Bit Plane Values",
522
+ "Error Level Analysis (ELA)",
523
+ "Gradient Processing",
524
+ "MinMax Processing"
525
+ ]
526
+ )
527
+
528
+ if __name__ == "__main__":
529
+ with CommitScheduler(
530
+ repo_id=HF_DATASET_NAME,
531
+ repo_type="dataset",
532
+ folder_path=LOCAL_LOG_DIR,
533
+ every=5,
534
+ private=False,
535
+ token=os.getenv("HF_TOKEN")
536
+ ) as scheduler:
537
+ demo.launch(mcp_server=True)