File size: 47,817 Bytes
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
 
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
 
a1674bb
 
 
 
 
bcb108a
a1674bb
 
 
 
22628b7
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
a1674bb
 
 
 
 
 
 
22628b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b7800e
22628b7
 
 
9b7800e
 
 
 
 
22628b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
 
 
a1674bb
 
 
 
22628b7
 
a1674bb
 
 
 
 
 
 
22628b7
a1674bb
 
 
22628b7
 
 
 
 
a1674bb
 
 
 
22628b7
 
 
 
 
 
 
 
 
a1674bb
 
 
 
 
 
 
 
22628b7
 
 
 
 
 
 
 
 
 
a1674bb
 
22628b7
 
 
 
 
 
 
 
 
 
 
 
a1674bb
22628b7
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
 
a1674bb
 
 
 
 
 
 
 
 
 
 
22628b7
 
a1674bb
 
 
 
 
 
22628b7
a1674bb
22628b7
a1674bb
 
22628b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1674bb
22628b7
 
 
 
 
 
a1674bb
 
 
 
 
22628b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1674bb
22628b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
 
 
 
 
 
 
 
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
 
 
 
 
 
 
 
 
 
a1674bb
 
 
22628b7
a1674bb
 
 
22628b7
a1674bb
 
 
 
22628b7
 
a1674bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22628b7
a1674bb
 
 
 
 
 
 
 
3b6c798
a1674bb
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
import gradio as gr
from gradio_client import Client, handle_file
from PIL import Image, ImageFilter
import numpy as np
import os
import time
import logging
import io
import collections
import onnxruntime
import json
from huggingface_hub import CommitScheduler, hf_hub_download, snapshot_download
from dotenv import load_dotenv
import concurrent.futures
import ast
import torch

from utils.utils import softmax, augment_image
from forensics.gradient import gradient_processing
from forensics.minmax import minmax_process
from forensics.ela import ELA
from forensics.wavelet import noise_estimation
from forensics.bitplane import bit_plane_extractor
from utils.hf_logger import log_inference_data
from utils.load import load_image
from agents.ensemble_team import EnsembleMonitorAgent, WeightOptimizationAgent, SystemHealthAgent
from agents.smart_agents import ContextualIntelligenceAgent, ForensicAnomalyDetectionAgent
from utils.registry import register_model, MODEL_REGISTRY, ModelEntry
from agents.ensemble_weights import ModelWeightManager
from transformers import pipeline, AutoImageProcessor, SwinForImageClassification, Swinv2ForImageClassification, AutoFeatureExtractor, AutoModelForImageClassification
from torchvision import transforms

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
os.environ['HF_HUB_CACHE'] = './models'

# --- Gradio Log Handler ---
class GradioLogHandler(logging.Handler):
    def __init__(self, log_queue):
        super().__init__()
        self.log_queue = log_queue
        self.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

    def emit(self, record):
        self.log_queue.append(self.format(record))

log_queue = collections.deque(maxlen=1000) # Store last 1000 log messages
gradio_handler = GradioLogHandler(log_queue)

# Set root logger level to DEBUG to capture all messages from agents
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(gradio_handler)
# --- End Gradio Log Handler ---

LOCAL_LOG_DIR = "./hf_inference_logs"
HF_DATASET_NAME="aiwithoutborders-xyz/degentic_rd0"
load_dotenv()

# Custom JSON Encoder to handle numpy types
class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.float32):
            return float(obj)
        return json.JSONEncoder.default(self, obj)

# Ensure using GPU if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Model paths and class names (copied from app_mcp.py)
MODEL_PATHS = {
    "model_1": "LPX55/detection-model-1-ONNX",
    "model_2": "LPX55/detection-model-2-ONNX",
    "model_3": "LPX55/detection-model-3-ONNX",
    "model_4": "cmckinle/sdxl-flux-detector_v1.1",
    "model_5": "LPX55/detection-model-5-ONNX",
    "model_6": "LPX55/detection-model-6-ONNX",
    "model_7": "LPX55/detection-model-7-ONNX",
    "model_8": "aiwithoutborders-xyz/CommunityForensics-DeepfakeDet-ViT"
}

CLASS_NAMES = {
    "model_1": ['artificial', 'real'],
    "model_2": ['AI Image', 'Real Image'],
    "model_3": ['artificial', 'human'],
    "model_4": ['AI', 'Real'],
    "model_5": ['Realism', 'Deepfake'],
    "model_6": ['ai_gen', 'human'],
    "model_7": ['Fake', 'Real'],
    "model_8": ['Fake', 'Real'],
}

def preprocess_resize_256(image):
    if image.mode != 'RGB':
        image = image.convert('RGB')
    return transforms.Resize((256, 256))(image)

def preprocess_resize_224(image):
    if image.mode != 'RGB':
        image = image.convert('RGB')
    return transforms.Resize((224, 224))(image)

def postprocess_pipeline(prediction, class_names):
    # Assumes HuggingFace pipeline output
    return {pred['label']: float(pred['score']) for pred in prediction}

def postprocess_logits(outputs, class_names):
    # Assumes model output with logits
    logits = outputs.logits.cpu().numpy()[0]
    probabilities = softmax(logits)
    return {class_names[i]: probabilities[i] for i in range(len(class_names))}

def postprocess_binary_output(output, class_names):
    # output can be a dictionary {"probabilities": numpy_array} or directly a numpy_array
    probabilities_array = None
    if isinstance(output, dict) and "probabilities" in output:
        probabilities_array = output["probabilities"]
    elif isinstance(output, np.ndarray):
        probabilities_array = output
    else:
        logger.warning(f"Unexpected output type for binary post-processing: {type(output)}. Expected dict with 'probabilities' or numpy.ndarray.")
        return {class_names[0]: 0.0, class_names[1]: 1.0}

    logger.info(f"Debug: Probabilities array entering postprocess_binary_output: {probabilities_array}, type: {type(probabilities_array)}, shape: {probabilities_array.shape}")

    if probabilities_array is None:
        logger.warning("Probabilities array is None after extracting from output. Returning default scores.")
        return {class_names[0]: 0.0, class_names[1]: 1.0}

    if probabilities_array.size == 1:
        fake_prob = float(probabilities_array.item())
    elif probabilities_array.size == 2:
        fake_prob = float(probabilities_array[0])
    else:
        logger.warning(f"Unexpected probabilities array shape for binary post-processing: {probabilities_array.shape}. Expected size 1 or 2.")
        return {class_names[0]: 0.0, class_names[1]: 1.0}

    real_prob = 1.0 - fake_prob # Ensure Fake and Real sum to 1
    return {class_names[0]: fake_prob, class_names[1]: real_prob}

def infer_gradio_api(image_path):
    client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
    result_dict = client.predict(
        input_image=handle_file(image_path),
        api_name="/simple_predict"
    )
    logger.info(f"Debug: Raw result_dict from Gradio API (model_8): {result_dict}, type: {type(result_dict)}")
    # result_dict is already a dictionary, no need for ast.literal_eval
    fake_probability = result_dict.get('Fake Probability', 0.0)
    logger.info(f"Debug: Parsed result_dict: {result_dict}, Extracted fake_probability: {fake_probability}")
    return {"probabilities": np.array([fake_probability])} # Return as a numpy array with one element

# New preprocess function for Gradio API
def preprocess_gradio_api(image: Image.Image):
    # The Gradio API expects a file path, so we need to save the PIL Image to a temporary file.
    temp_file_path = "./temp_gradio_input.png"
    image.save(temp_file_path)
    return temp_file_path

# New postprocess function for Gradio API (adapting postprocess_binary_output)
def postprocess_gradio_api(gradio_output, class_names):
    # gradio_output is expected to be a dictionary like {"probabilities": np.array([fake_prob])}
    probabilities_array = None
    if isinstance(gradio_output, dict) and "probabilities" in gradio_output:
        probabilities_array = gradio_output["probabilities"]
    elif isinstance(gradio_output, np.ndarray):
        probabilities_array = gradio_output
    else:
        logger.warning(f"Unexpected output type for Gradio API post-processing: {type(gradio_output)}. Expected dict with 'probabilities' or numpy.ndarray.")
        return {class_names[0]: 0.0, class_names[1]: 1.0}

    logger.info(f"Debug: Probabilities array entering postprocess_gradio_api: {probabilities_array}, type: {type(probabilities_array)}, shape: {probabilities_array.shape}")

    if probabilities_array is None or probabilities_array.size == 0:
        logger.warning("Probabilities array is None or empty after extracting from Gradio API output. Returning default scores.")
        return {class_names[0]: 0.0, class_names[1]: 1.0}

    # It should always be a single element array for fake probability
    fake_prob = float(probabilities_array.item())
    real_prob = 1.0 - fake_prob

    return {class_names[0]: fake_prob, class_names[1]: real_prob}

def register_model_with_metadata(model_id, model, preprocess, postprocess, class_names, display_name, contributor, model_path, architecture=None, dataset=None):
    entry = ModelEntry(model, preprocess, postprocess, class_names, display_name=display_name, contributor=contributor, model_path=model_path, architecture=architecture, dataset=dataset)
    MODEL_REGISTRY[model_id] = entry


def load_onnx_model_and_preprocessor(hf_model_id):
    # model_dir = snapshot_download(repo_id=hf_model_id, local_dir_use_symlinks=False)
    
    # Create a unique local directory for each ONNX model
    model_specific_dir = os.path.join("./models", hf_model_id.replace('/', '_'))
    os.makedirs(model_specific_dir, exist_ok=True)

    # Use hf_hub_download to get specific files into the model-specific directory
    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)

    # Load preprocessor config
    preprocessor_config = {}
    try:
        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)
        with open(preprocessor_config_path, 'r') as f:
            preprocessor_config = json.load(f)
    except Exception as e:
        logger.warning(f"Could not download or load preprocessor_config.json for {hf_model_id}: {e}")
    
    # Load model config for class names if available
    model_config = {}
    try:
        model_config_path = hf_hub_download(repo_id=hf_model_id, filename="config.json", local_dir=model_specific_dir, local_dir_use_symlinks=False)
        with open(model_config_path, 'r') as f:
            model_config = json.load(f)
    except Exception as e:
        logger.warning(f"Could not download or load config.json for {hf_model_id}: {e}")

    return onnxruntime.InferenceSession(onnx_model_path), preprocessor_config, model_config


# Cache for ONNX sessions and preprocessors
_onnx_model_cache = {}

def get_onnx_model_from_cache(hf_model_id):
    if hf_model_id not in _onnx_model_cache:
        logger.info(f"Loading ONNX model and preprocessor for {hf_model_id}...")
        _onnx_model_cache[hf_model_id] = load_onnx_model_and_preprocessor(hf_model_id)
    return _onnx_model_cache[hf_model_id]

def preprocess_onnx_input(image: Image.Image, preprocessor_config: dict):
    # Preprocess image for ONNX model based on preprocessor_config
    if image.mode != 'RGB':
        image = image.convert('RGB')
    
    # Get image size and normalization values from preprocessor_config or use defaults
    # Use 'size' for initial resize and 'crop_size' for center cropping
    initial_resize_size = preprocessor_config.get('size', {'height': 224, 'width': 224})
    crop_size = preprocessor_config.get('crop_size', initial_resize_size['height'])
    mean = preprocessor_config.get('image_mean', [0.485, 0.456, 0.406])
    std = preprocessor_config.get('image_std', [0.229, 0.224, 0.225])

    transform = transforms.Compose([
        transforms.Resize((initial_resize_size['height'], initial_resize_size['width'])),
        transforms.CenterCrop(crop_size), # Apply center crop
        transforms.ToTensor(),
        transforms.Normalize(mean=mean, std=std),
    ])
    input_tensor = transform(image)
    # ONNX expects numpy array with batch dimension (1, C, H, W)
    return input_tensor.unsqueeze(0).cpu().numpy()

def infer_onnx_model(hf_model_id, preprocessed_image_np, model_config: dict):
    try:
        ort_session, _, _ = get_onnx_model_from_cache(hf_model_id)
        
        # Debug: Print expected input shape from ONNX model
        for input_meta in ort_session.get_inputs():
            logger.info(f"Debug: ONNX model expected input name: {input_meta.name}, shape: {input_meta.shape}, type: {input_meta.type}")

        logger.info(f"Debug: preprocessed_image_np shape: {preprocessed_image_np.shape}")
        ort_inputs = {ort_session.get_inputs()[0].name: preprocessed_image_np}
        ort_outputs = ort_session.run(None, ort_inputs)
        
        logits = ort_outputs[0]
        logger.info(f"Debug: logits type: {type(logits)}, shape: {logits.shape}")
        # If the model outputs a single logit (e.g., shape (1,)), use .item() to convert to scalar
        # Otherwise, assume it's a batch of logits (e.g., shape (1, num_classes)) and take the first element (batch dim)
        # The num_classes in config.json can be misleading; rely on actual output shape.
        
        # Apply softmax to the logits to get probabilities for the classes
        # The softmax function in utils/utils.py now ensures a list of floats
        probabilities = softmax(logits[0]) # Assuming logits[0] is the relevant output for a single prediction

        return {"logits": logits, "probabilities": probabilities}

    except Exception as e:
        logger.error(f"Error during ONNX inference for {hf_model_id}: {e}")
        # Return a structure consistent with other model errors
        return {"logits": np.array([]), "probabilities": np.array([])}

def postprocess_onnx_output(onnx_output, model_config):
    # Get class names from model_config
    # Prioritize id2label, then check num_classes, otherwise default
    class_names_map = model_config.get('id2label')
    if class_names_map:
        class_names = [class_names_map[k] for k in sorted(class_names_map.keys())]
    elif model_config.get('num_classes') == 1: # Handle models that output a single value (e.g., probability of 'Fake')
        class_names = ['Fake', 'Real'] # Assume first class is 'Fake' and second 'Real'
    else:
        class_names = {0: 'Fake', 1: 'Real'} # Default to Fake/Real if not found or not 1 class
        class_names = [class_names[i] for i in sorted(class_names.keys())]

    probabilities = onnx_output.get("probabilities")
    
    if probabilities is not None:
        if model_config.get('num_classes') == 1 and len(probabilities) == 2: # Special handling for single output models
            # The single output is the probability of the 'Fake' class
            fake_prob = float(probabilities[0])
            real_prob = float(probabilities[1])
            return {class_names[0]: fake_prob, class_names[1]: real_prob}
        elif len(probabilities) == len(class_names):
            return {class_names[i]: float(probabilities[i]) for i in range(len(class_names))}
        else:
            logger.warning("ONNX post-processing: Probabilities length mismatch with class names.")
            return {name: 0.0 for name in class_names}
    else:
        logger.warning("ONNX post-processing failed: 'probabilities' key not found in output.")
        return {name: 0.0 for name in class_names}

# Register the ONNX quantized model
# Dummy entry for ONNX model to be loaded dynamically
# We will now register a 'wrapper' that handles dynamic loading

class ONNXModelWrapper:
    def __init__(self, hf_model_id):
        self.hf_model_id = hf_model_id
        self._session = None
        self._preprocessor_config = None
        self._model_config = None

    def load(self):
        if self._session is None:
            self._session, self._preprocessor_config, self._model_config = get_onnx_model_from_cache(self.hf_model_id)
            logger.info(f"ONNX model {self.hf_model_id} loaded into wrapper.")

    def __call__(self, image_np):
        self.load() # Ensure model is loaded on first call
        # Pass model_config to infer_onnx_model
        return infer_onnx_model(self.hf_model_id, image_np, self._model_config)

    def preprocess(self, image: Image.Image):
        self.load()
        return preprocess_onnx_input(image, self._preprocessor_config)

    def postprocess(self, onnx_output: dict, class_names_from_registry: list): # class_names_from_registry is ignored
        self.load()
        return postprocess_onnx_output(onnx_output, self._model_config)

# Consolidate all model loading and registration
for model_key, hf_model_path in MODEL_PATHS.items():
    logger.debug(f"Attempting to register model: {model_key} with path: {hf_model_path}")
    model_num = model_key.replace("model_", "").upper()
    contributor = "Unknown"
    architecture = "Unknown"
    dataset = "TBA"

    current_class_names = CLASS_NAMES.get(model_key, [])

    # Logic for ONNX models (1, 2, 3, 5, 6, 7)
    if "ONNX" in hf_model_path:
        logger.debug(f"Model {model_key} identified as ONNX.")
        logger.info(f"Registering ONNX model: {model_key} from {hf_model_path}")
        onnx_wrapper_instance = ONNXModelWrapper(hf_model_path)

        # Attempt to derive contributor, architecture, dataset based on model_key
        if model_key == "model_1":
            contributor = "haywoodsloan"
            architecture = "SwinV2"
            dataset = "DeepFakeDetection"
        elif model_key == "model_2":
            contributor = "Heem2"
            architecture = "ViT"
            dataset = "DeepFakeDetection"
        elif model_key == "model_3":
            contributor = "Organika"
            architecture = "VIT"
            dataset = "SDXL"
        elif model_key == "model_5":
            contributor = "prithivMLmods"
            architecture = "VIT"
        elif model_key == "model_6":
            contributor = "ideepankarsharma2003"
            architecture = "SWINv1"
            dataset = "SDXL, Midjourney"
        elif model_key == "model_7":
            contributor = "date3k2"
            architecture = "VIT"

        display_name_parts = [model_num]
        if architecture and architecture not in ["Unknown"]:
            display_name_parts.append(architecture)
        if dataset and dataset not in ["TBA"]:
            display_name_parts.append(dataset)
        display_name = "-".join(display_name_parts)
        display_name += "_ONNX" # Always append _ONNX for ONNX models

        register_model_with_metadata(
            model_id=model_key,
            model=onnx_wrapper_instance, # The callable wrapper for the ONNX model
            preprocess=onnx_wrapper_instance.preprocess,
            postprocess=onnx_wrapper_instance.postprocess,
            class_names=current_class_names, # Initial class names; will be overridden by model_config if available
            display_name=display_name,
            contributor=contributor,
            model_path=hf_model_path,
            architecture=architecture,
            dataset=dataset
        )
    # Logic for Gradio API model (model_8)
    elif model_key == "model_8":
        logger.debug(f"Model {model_key} identified as Gradio API.")
        logger.info(f"Registering Gradio API model: {model_key} from {hf_model_path}")
        contributor = "aiwithoutborders-xyz"
        architecture = "ViT"
        dataset = "DeepfakeDetection"

        display_name_parts = [model_num]
        if architecture and architecture not in ["Unknown"]:
            display_name_parts.append(architecture)
        if dataset and dataset not in ["TBA"]:
            display_name_parts.append(dataset)
        display_name = "-".join(display_name_parts)

        register_model_with_metadata(
            model_id=model_key,
            model=infer_gradio_api,
            preprocess=preprocess_gradio_api,
            postprocess=postprocess_gradio_api,
            class_names=current_class_names,
            display_name=display_name,
            contributor=contributor,
            model_path=hf_model_path,
            architecture=architecture,
            dataset=dataset
        )
    # Logic for PyTorch/Hugging Face pipeline models (currently only model_4)
    elif model_key == "model_4": # Explicitly handle model_4
        logger.debug(f"Model {model_key} identified as PyTorch/HuggingFace pipeline.")
        logger.info(f"Registering HuggingFace pipeline/AutoModel: {model_key} from {hf_model_path}")
        contributor = "cmckinle"
        architecture = "VIT"
        dataset = "SDXL, FLUX"

        display_name_parts = [model_num]
        if architecture and architecture not in ["Unknown"]:
            display_name_parts.append(architecture)
        if dataset and dataset not in ["TBA"]:
            display_name_parts.append(dataset)
        display_name = "-".join(display_name_parts)

        current_processor = AutoFeatureExtractor.from_pretrained(hf_model_path, device=device)
        model_instance = AutoModelForImageClassification.from_pretrained(hf_model_path).to(device)

        preprocess_func = preprocess_resize_256
        postprocess_func = postprocess_logits

        def custom_infer(image, processor_local=current_processor, model_local=model_instance):
            inputs = processor_local(image, return_tensors="pt").to(device)
            with torch.no_grad():
                outputs = model_local(**inputs)
            return outputs
        model_instance = custom_infer

        register_model_with_metadata(
            model_id=model_key,
            model=model_instance,
            preprocess=preprocess_func,
            postprocess=postprocess_func,
            class_names=current_class_names,
            display_name=display_name,
            contributor=contributor,
            model_path=hf_model_path,
            architecture=architecture,
            dataset=dataset
        )
    else: # Fallback for any unhandled models (shouldn't happen if MODEL_PATHS is fully covered)
        logger.warning(f"Could not automatically load and register model: {model_key} from {hf_model_path}. No matching registration logic found.")


def infer(image: Image.Image, model_id: str, confidence_threshold: float = 0.75) -> dict:
    """Predict using a specific model.

    Args:
        image (Image.Image): The input image to classify.
        model_id (str): The ID of the model to use for classification.
        confidence_threshold (float, optional): The confidence threshold for classification. Defaults to 0.75.

    Returns:
        dict: A dictionary containing the model details, classification scores, and label.
    """
    entry = MODEL_REGISTRY[model_id]
    img = entry.preprocess(image) if entry.preprocess else image
    try:
        result = entry.model(img)
        scores = entry.postprocess(result, entry.class_names)
        
        def _to_float_scalar(value):
            if isinstance(value, np.ndarray):
                return float(value.item()) # Convert numpy array scalar to Python float
            return float(value) # Already a Python scalar or convertible type

        ai_score = _to_float_scalar(scores.get(entry.class_names[0], 0.0))
        real_score = _to_float_scalar(scores.get(entry.class_names[1], 0.0))
        label = "AI" if ai_score >= confidence_threshold else ("REAL" if real_score >= confidence_threshold else "UNCERTAIN")
        return {
            "Model": entry.display_name,
            "Contributor": entry.contributor,
            "HF Model Path": entry.model_path,
            "AI Score": ai_score,
            "Real Score": real_score,
            "Label": label
        }
    except Exception as e:
        return {
            "Model": entry.display_name,
            "Contributor": entry.contributor,
            "HF Model Path": entry.model_path,
            "AI Score": 0.0,
            "Real Score": 0.0,
            "Label": f"Error: {str(e)}"
        }

def full_prediction(img, confidence_threshold, rotate_degrees, noise_level, sharpen_strength):
    """Full prediction run, with a team of ensembles and agents.

    Args:
        img (url: str, Image.Image, np.ndarray): The input image to classify.
        confidence_threshold (float, optional): The confidence threshold for classification. Defaults to 0.75.
        rotate_degrees (int, optional): The degrees to rotate the image.
        noise_level (int, optional): The noise level to use.
        sharpen_strength (int, optional): The sharpen strength to use.

    Returns:
        dict: A dictionary containing the model details, classification scores, and label.
    """
    # Ensure img is a PIL Image object
    if img is None:
        raise gr.Error("No image provided. Please upload an image to analyze.")
    # Handle filepath conversion if needed
    if isinstance(img, str):
        try:
            img = load_image(img)
        except Exception as e:
            logger.error(f"Error loading image from path: {e}")
            raise gr.Error(f"Could not load image from the provided path. Error: {str(e)}")
        
    if not isinstance(img, Image.Image):
        try:
            img = Image.fromarray(img)
        except Exception as e:
            logger.error(f"Error converting input image to PIL: {e}")
            raise gr.Error("Input image could not be converted to a valid image format. Please try another image.")

    # Ensure image is in RGB format for consistent processing
    if img.mode != 'RGB':
        img = img.convert('RGB')

    monitor_agent = EnsembleMonitorAgent()
    weight_manager = ModelWeightManager(strongest_model_id="simple_prediction")
    optimization_agent = WeightOptimizationAgent(weight_manager)
    health_agent = SystemHealthAgent()
    context_agent = ContextualIntelligenceAgent()
    anomaly_agent = ForensicAnomalyDetectionAgent()
    health_agent.monitor_system_health()
    if rotate_degrees or noise_level or sharpen_strength:
        img_pil, _ = augment_image(img, ["rotate", "add_noise", "sharpen"], rotate_degrees, noise_level, sharpen_strength)
    else:
        img_pil = img
    img_np_og = np.array(img)

    model_predictions_raw = {}
    confidence_scores = {}
    results = []
    table_rows = []

    # Initialize lists for forensic outputs, starting with the original augmented image
    cleaned_forensics_images = []
    forensic_output_descriptions = []

    # Always add the original augmented image first for forensic display
    if isinstance(img_pil, Image.Image):
        cleaned_forensics_images.append(img_pil)
        forensic_output_descriptions.append(f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}")
    elif isinstance(img_pil, np.ndarray):
        try:
            pil_img_from_np = Image.fromarray(img_pil)
            cleaned_forensics_images.append(pil_img_from_np)
            forensic_output_descriptions.append(f"Original augmented image (numpy converted to PIL): {pil_img_from_np.width}x{pil_img_from_np.height}")
        except Exception as e:
            logger.warning(f"Could not convert original numpy image to PIL for gallery: {e}")
    
    # Yield initial state with augmented image and empty model predictions
    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>"


    # Stream results as each model finishes
    for model_id in MODEL_REGISTRY:
        model_start = time.time()
        result = infer(img_pil, model_id, confidence_threshold)
        model_end = time.time()

        # Helper to ensure values are Python floats, handling numpy scalars
        def _ensure_float_scalar(value):
            if isinstance(value, np.ndarray):
                return float(value.item()) # Convert numpy array scalar to Python float
            return float(value) # Already a Python scalar or convertible type

        ai_score_val = _ensure_float_scalar(result.get("AI Score", 0.0))
        real_score_val = _ensure_float_val = _ensure_float_scalar(result.get("Real Score", 0.0))

        monitor_agent.monitor_prediction(
            model_id,
            result["Label"],
            max(ai_score_val, real_score_val),
            model_end - model_start
        )
        model_predictions_raw[model_id] = result
        confidence_scores[model_id] = max(ai_score_val, real_score_val)
        results.append(result)
        table_rows.append([
            result.get("Model", ""),
            result.get("Contributor", ""),
            round(ai_score_val, 5),
            round(real_score_val, 5),
            result.get("Label", "Error")
        ])
        # Yield partial results: only update the table, others are None
        yield None, cleaned_forensics_images, table_rows, None, None # Keep cleaned_forensics_images as is (only augmented image for now)

    # Multi-threaded forensic processing
    def _run_forensic_task(task_func, img_input, description, **kwargs):
        try:
            result_img = task_func(img_input, **kwargs)
            return result_img, description
        except Exception as e:
            logger.error(f"Error processing forensic task {task_func.__name__}: {e}")
            return None, f"Error processing {description}: {str(e)}"

    with concurrent.futures.ThreadPoolExecutor() as executor:
        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)
        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)
        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)
        future_gradient1 = executor.submit(_run_forensic_task, gradient_processing, img_np_og, "Gradient processing: Highlights edges and transitions.")
        future_gradient2 = executor.submit(_run_forensic_task, gradient_processing, img_np_og, "Gradient processing: Int=45, Equalize=True", intensity=45, equalize=True)
        future_minmax1 = executor.submit(_run_forensic_task, minmax_process, img_np_og, "MinMax processing: Deviations in local pixel values.")
        future_minmax2 = executor.submit(_run_forensic_task, minmax_process, img_np_og, "MinMax processing (Radius=6): Deviations in local pixel values.", radius=6)

        forensic_futures = [future_ela1, future_ela2, future_ela3, future_gradient1, future_gradient2, future_minmax1, future_minmax2]
        
        for future in concurrent.futures.as_completed(forensic_futures):
            processed_img, description = future.result()
            if processed_img is not None:
                if isinstance(processed_img, Image.Image):
                    cleaned_forensics_images.append(processed_img)
                elif isinstance(processed_img, np.ndarray):
                    try:
                        cleaned_forensics_images.append(Image.fromarray(processed_img))
                    except Exception as e:
                        logger.warning(f"Could not convert numpy array to PIL Image for gallery: {e}")
                else:
                    logger.warning(f"Unexpected type in processed_img from {description}: {type(processed_img)}. Skipping.")
                
                forensic_output_descriptions.append(description) # Keep track of descriptions for anomaly agent
                
                # Yield partial results: update gallery
                yield None, cleaned_forensics_images, table_rows, None, None

    # After all models, compute the rest as before
    image_data_for_context = {
        "width": img.width,
        "height": img.height,
        "mode": img.mode,
    }
    forensic_output_descriptions = [
        f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
        "ELA analysis (Pass 1): Grayscale error map, quality 75.",
        "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
        "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
        "Gradient processing: Highlights edges and transitions.",
        "Gradient processing: Int=45, Equalize=True",
        "MinMax processing: Deviations in local pixel values.",
        "MinMax processing (Radius=6): Deviations in local pixel values.",
        # "Bit Plane extractor: Visualization of individual bit planes from different color channels."
    ]
    detected_context_tags = context_agent.infer_context_tags(image_data_for_context, model_predictions_raw)
    logger.info(f"Detected context tags: {detected_context_tags}")
    adjusted_weights = weight_manager.adjust_weights(model_predictions_raw, confidence_scores, context_tags=detected_context_tags)
    weighted_predictions = {"AI": 0.0, "REAL": 0.0, "UNCERTAIN": 0.0}
    for model_id, prediction in model_predictions_raw.items():
        prediction_label = prediction.get("Label")
        if prediction_label in weighted_predictions:
            weighted_predictions[prediction_label] += adjusted_weights[model_id]
        else:
            logger.warning(f"Unexpected prediction label '{prediction_label}' from model '{model_id}'. Skipping its weight in consensus.")
    final_prediction_label = "UNCERTAIN"
    if weighted_predictions["AI"] > weighted_predictions["REAL"] and weighted_predictions["AI"] > weighted_predictions["UNCERTAIN"]:
        final_prediction_label = "AI"
    elif weighted_predictions["REAL"] > weighted_predictions["AI"] and weighted_predictions["REAL"] > weighted_predictions["UNCERTAIN"]:
        final_prediction_label = "REAL"
    optimization_agent.analyze_performance(final_prediction_label, None)
    # gradient_image = gradient_processing(img_np_og)
    # gradient_image2 = gradient_processing(img_np_og, intensity=45, equalize=True)
    # minmax_image = minmax_process(img_np_og)
    # minmax_image2 = minmax_process(img_np_og, radius=6)
    # # bitplane_image = bit_plane_extractor(img_pil)
    # ela1 = ELA(img_np_og, quality=75, scale=50, contrast=20, linear=False, grayscale=True)
    # ela2 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=True)
    # ela3 = ELA(img_np_og, quality=75, scale=75, contrast=25, linear=False, grayscale=False)
    # forensics_images = [img_pil, ela1, ela2, ela3, gradient_image, gradient_image2, minmax_image, minmax_image2]
    # forensic_output_descriptions = [
    #     f"Original augmented image (PIL): {img_pil.width}x{img_pil.height}",
    #     "ELA analysis (Pass 1): Grayscale error map, quality 75.",
    #     "ELA analysis (Pass 2): Grayscale error map, quality 75, enhanced contrast.",
    #     "ELA analysis (Pass 3): Color error map, quality 75, enhanced contrast.",
    #     "Gradient processing: Highlights edges and transitions.",
    #     "Gradient processing: Int=45, Equalize=True",
    #     "MinMax processing: Deviations in local pixel values.",
    #     "MinMax processing (Radius=6): Deviations in local pixel values.",
    #     # "Bit Plane extractor: Visualization of individual bit planes from different color channels."
    # ]
    anomaly_detection_results = anomaly_agent.analyze_forensic_outputs(forensic_output_descriptions)
    logger.info(f"Forensic anomaly detection: {anomaly_detection_results['summary']}")
    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>"
    inference_params = {
        "confidence_threshold": confidence_threshold,
        "rotate_degrees": rotate_degrees,
        "noise_level": noise_level,
        "sharpen_strength": sharpen_strength,
        "detected_context_tags": detected_context_tags
    }
    ensemble_output_data = {
        "final_prediction_label": final_prediction_label,
        "weighted_predictions": weighted_predictions,
        "adjusted_weights": adjusted_weights
    }
    agent_monitoring_data_log = {
        "ensemble_monitor": {
            "alerts": monitor_agent.alerts,
            "performance_metrics": monitor_agent.performance_metrics
        },
        "weight_optimization": {
            "prediction_history_length": len(optimization_agent.prediction_history),
        },
        "system_health": {
            "memory_usage": health_agent.health_metrics["memory_usage"],
            "gpu_utilization": health_agent.health_metrics["gpu_utilization"]
        },
        "context_intelligence": {
            "detected_context_tags": detected_context_tags
        },
        "forensic_anomaly_detection": anomaly_detection_results
    }
    log_inference_data(
        original_image=img,
        inference_params=inference_params,
        model_predictions=results,
        ensemble_output=ensemble_output_data,
        forensic_images=cleaned_forensics_images, # Use the incrementally built list
        agent_monitoring_data=agent_monitoring_data_log,
        human_feedback=None
    )

    logger.info(f"Cleaned forensic images types: {[type(img) for img in cleaned_forensics_images]}")
    for i, res_dict in enumerate(results):
        for key in ["AI Score", "Real Score"]:
            value = res_dict.get(key)
            if isinstance(value, np.float32):
                res_dict[key] = float(value)
                logger.info(f"Converted {key} for result {i} from numpy.float32 to float.")
    json_results = json.dumps(results, cls=NumpyEncoder)
    yield img_pil, cleaned_forensics_images, table_rows, json_results, consensus_html

detection_model_eval_playground = gr.Interface(
    fn=full_prediction,
    inputs=[
        gr.Image(label="Upload Image to Analyze", sources=['upload', 'webcam'], type='filepath'),
        gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Confidence Threshold"),
        gr.Slider(0, 45, value=0, step=1, label="Rotate Degrees", visible=False),
        gr.Slider(0, 50, value=0, step=1, label="Noise Level", visible=False),
        gr.Slider(0, 50, value=0, step=1, label="Sharpen Strength", visible=False)
    ],
    outputs=[
        gr.Image(label="Processed Image", visible=False),
        gr.Gallery(label="Post Processed Images", visible=True, columns=[4], rows=[2], container=False, height="auto", object_fit="contain", elem_id="post-gallery"),
        gr.Dataframe(
            label="Model Predictions",
            headers=["Arch / Dataset", "By", "AI", "Real", "Label"],
            datatype=["str", "str", "number", "number", "str"]
        ),
        gr.JSON(label="Raw Model Results", visible=False),
        gr.Markdown(label="Consensus", value="")
    ],
    title="Multi-Model Ensemble + Agentic Coordinated Deepfake Detection (Paper in Progress)",
    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.",
    api_name="predict",
    live=True  # Enable streaming
)
# def echo_headers(x, request: gr.Request):
#     print(dict(request.headers))
#     return str(dict(request.headers))


def predict(img):
    """
    Predicts whether an image is AI-generated or real using the SOTA Community Forensics model.

    Args:
        img (str): Path to the input image file to analyze.

    Returns:
        dict: A dictionary containing:
            - 'Fake Probability' (float): Probability score between 0 and 1 indicating likelihood of being AI-generated
            - 'Result Description' (str): Human-readable description of the prediction result

    Example:
        >>> result = predict("path/to/image.jpg")
        >>> print(result)
        {'Fake Probability': 0.002, 'Result Description': 'The image is likely real.'}
    """
    client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
    client.view_api()
    result = client.predict(
        handle_file(img),
        api_name="/simple_predict"
    )
    return str(result)
community_forensics_preview = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="filepath"),
    outputs=gr.HTML(), # or gr.Markdown() if it's just text
    title="Quick and simple prediction by our strongest model.",
    description="No ensemble, no context, no agents, just a quick and simple prediction by our strongest model.",
    api_name="predict"
)

# leaderboard = gr.Interface(
#     fn=lambda: "# AI Generated / Deepfake Detection Models Leaderboard: Soon™",
#     inputs=None,
#     outputs=gr.Markdown(),
#     title="Leaderboard",
#     api_name="leaderboard"
# )
def simple_prediction(img):
    """
    Quick and simple deepfake or real image prediction by the strongest open-source model on the hub.

    Args:
        img (str): The input image to analyze, provided as a file path.

    Returns:
        str: The prediction result stringified from dict. Example: `{'Fake Probability': 0.002, 'Result Description': 'The image is likely real.'}`
    """    
    client = Client("aiwithoutborders-xyz/OpenSight-Community-Forensics-Preview")
    client.view_api()
    client.predict(
        handle_file(img),
        api_name="simple_predict"
    )
simple_predict_interface = gr.Interface(
    fn=simple_prediction,
    inputs=gr.Image(type="filepath"),
    outputs=gr.Text(),
    title="Quick and simple prediction by our strongest model.",
    description="No ensemble, no context, no agents, just a quick and simple prediction by our strongest model.",
    api_name="simple_predict"
)

noise_estimation_interface = gr.Interface(
    fn=noise_estimation,
    inputs=[gr.Image(type="pil"), gr.Slider(1, 32, value=8, step=1, label="Block Size")],
    outputs=gr.Image(type="pil"),
    title="Wavelet-Based Noise Analysis",
    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.",
    api_name="tool_waveletnoise"
)

bit_plane_interface = gr.Interface(
    fn=bit_plane_extractor,
    inputs=[
        gr.Image(type="pil"),
        gr.Dropdown(["Luminance", "Red", "Green", "Blue", "RGB Norm"], label="Channel", value="Luminance"),
        gr.Slider(0, 7, value=0, step=1, label="Bit Plane"),
        gr.Dropdown(["Disabled", "Median", "Gaussian"], label="Filter", value="Disabled")
    ],
    outputs=gr.Image(type="pil"),
    title="Bit Plane Analysis",
    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.",
    api_name="tool_bitplane"
)

ela_interface = gr.Interface(
    fn=ELA,
    inputs=[
        gr.Image(type="pil", label="Input Image"),
        gr.Slider(1, 100, value=75, step=1, label="JPEG Quality"),
        gr.Slider(1, 100, value=50, step=1, label="Output Scale (Multiplicative Gain)"),
        gr.Slider(0, 100, value=20, step=1, label="Output Contrast (Tonality Compression)"),
        gr.Checkbox(value=False, label="Use Linear Difference"),
        gr.Checkbox(value=False, label="Grayscale Output")
    ],
    outputs=gr.Image(type="pil"),
    title="Error Level Analysis (ELA)",
    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.",
    api_name="tool_ela"
)

gradient_processing_interface = gr.Interface(
    fn=gradient_processing,
    inputs=[
        gr.Image(type="pil", label="Input Image"),
        gr.Slider(0, 100, value=90, step=1, label="Intensity"),
        gr.Dropdown(["Abs", "None", "Flat", "Norm"], label="Blue Mode", value="Abs"),
        gr.Checkbox(value=False, label="Invert Gradients"),
        gr.Checkbox(value=False, label="Equalize Histogram")
    ],
    outputs=gr.Image(type="pil"),
    title="Gradient Processing",
    description="Applies gradient filters to an image to enhance edges and transitions, which can reveal inconsistencies due to manipulation.",
    api_name="tool_gradient_processing"
)

minmax_processing_interface = gr.Interface(
    fn=minmax_process,
    inputs=[
        gr.Image(type="pil", label="Input Image"),
        gr.Radio([0, 1, 2, 3, 4], label="Channel (0:Grayscale, 1:Blue, 2:Green, 3:Red, 4:RGB Norm)", value=4),
        gr.Slider(0, 10, value=2, step=1, label="Radius")
    ],
    outputs=gr.Image(type="pil"),
    title="MinMax Processing",
    description="Analyzes local pixel value deviations to detect subtle changes in image data, often indicative of digital forgeries.",
    api_name="tool_minmax_processing"
)

# augmentation_tool_interface = gr.Interface(
#     fn=augment_image,
#     inputs=[
#         gr.Image(label="Upload Image to Augment", sources=['upload', 'webcam'], type='pil'),
#         gr.CheckboxGroup(["rotate", "add_noise", "sharpen"], label="Augmentation Methods"),
#         gr.Slider(0, 360, value=0, step=1, label="Rotate Degrees", visible=True),
#         gr.Slider(0, 100, value=0, step=1, label="Noise Level", visible=True),
#         gr.Slider(0, 200, value=1, step=1, label="Sharpen Strength", visible=True)
#     ],
#     outputs=gr.Image(label="Augmented Image", type='pil'),
#     title="Image Augmentation Tool",
#     description="Apply various augmentation techniques to your image.",
#     api_name="augment_image"
# )

# def get_captured_logs():
#     # Retrieve all logs from the queue and clear it
#     logs = list(log_queue)
#     log_queue.clear() # Clear the queue after retrieving
#     return "\n".join(logs)


demo = gr.TabbedInterface(
    [
        detection_model_eval_playground,
        community_forensics_preview,
        noise_estimation_interface,
        bit_plane_interface,
        ela_interface,
        gradient_processing_interface,
        minmax_processing_interface,
        # gr.Textbox(label="Agent Logs", interactive=False, lines=5, max_lines=20, autoscroll=True) # New textbox for logs
    ],
    [
        "Run Ensemble Prediction",
        "Open-Source SOTA Model",
        "Wavelet Blocking Noise Estimation",
        "Bit Plane Values",
        "Error Level Analysis (ELA)",
        "Gradient Processing",
        "MinMax Processing",
        # "Agent Logs" # New tab title
    ],
    title="Deepfake Detection & Forensics Tools",
    theme=None,

)
footerMD = """
## ⚠️ ENSEMBLE TEAM IN TRAINING ⚠️ \n\n

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.**
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.
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.

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)

"""
footer = gr.Markdown(footerMD, elem_classes="footer")

with gr.Blocks() as app:
    demo.render()
    footer.render()
    

app.queue(max_size=10, default_concurrency_limit=2).launch(mcp_server=True)