Spaces:
Running
Running
File size: 55,543 Bytes
368b41d | 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 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 | """
src/model.py
Contains modular functions:
- load_model_from_checkpoint
- build_model / build_xception_model
- preprocess_input
- train_model / train_model_with_dataset
- evaluate_model
- predict_from_input
- load_dataset_from_folder
This file is written to be general and self-contained, with sensible defaults.
Enhanced with Xception transfer learning for 90+ accuracy.
"""
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# ---------------------------------------------------------------------------
# TensorFlow / Keras compatibility
# ---------------------------------------------------------------------------
# The trained `.h5` models in this project (especially the HYBRID model)
# were created with the legacy TF‑Keras stack. Newer Keras 3 "safe" loading
# can choke on `Lambda` layers and raise errors like:
# "We could not automatically infer the shape of the Lambda's output".
# Enabling legacy Keras restores the old, backwards‑compatible behaviour
# and lets us load those checkpoints without changing them.
os.environ.setdefault("TF_USE_LEGACY_KERAS", "1")
# Try to import TensorFlow/Keras; if not available, provide informative errors.
try:
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.applications import Xception, EfficientNetB4, ResNet50
from tensorflow.keras.applications.xception import preprocess_input as xception_preprocess
from tensorflow.keras.applications.efficientnet import preprocess_input as efficientnet_preprocess
from tensorflow.keras.applications.resnet50 import preprocess_input as resnet_preprocess
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
except Exception as e:
tf = None
models = None
layers = None
Xception = None
EfficientNetB4 = None
ResNet50 = None
xception_preprocess = None
efficientnet_preprocess = None
resnet_preprocess = None
# Try to import cv2 for image and video loading
try:
import cv2
except Exception as e:
cv2 = None
# Try to import InceptionV3 for video feature extraction
try:
from tensorflow.keras.applications import InceptionV3
from tensorflow.keras.applications.inception_v3 import preprocess_input as inception_preprocess
except Exception as e:
InceptionV3 = None
inception_preprocess = None
def preprocess_input(x, use_xception=False, use_hybrid=False):
"""
Preprocess input numpy array (images or video frames).
Expects x as np.ndarray with shape (H,W,3) or (N,H,W,3).
Args:
x: Input image(s) as numpy array
use_xception: If True, uses Xception preprocessing (scales to [-1, 1])
If False, normalizes to [0, 1] (default for simple models)
use_hybrid: If True, uses preprocessing suitable for hybrid models
(Hybrid models handle preprocessing internally via augmentation layers)
Returns float32 array normalized appropriately.
"""
x = np.asarray(x, dtype=np.float32)
if use_hybrid:
# Hybrid models expect input in [0, 255] range, they handle preprocessing internally
# Ensure input is in [0, 255] range (if already normalized, scale back)
if x.ndim == 3:
x = np.expand_dims(x, 0)
# If values are in [0, 1] range, scale to [0, 255]
if x.max() <= 1.0:
x = x * 255.0
# Ensure dtype is float32
x = x.astype(np.float32)
elif use_xception and xception_preprocess is not None:
# Xception preprocessing: scales to [-1, 1]
if x.ndim == 3:
x = np.expand_dims(x, 0)
x = xception_preprocess(x)
else:
# Simple normalization to [0, 1]
if x.ndim == 3:
x = x / 255.0
x = np.expand_dims(x, 0)
else:
x = x / 255.0
return x
def build_simple_cnn(input_shape=(224,224,3), num_classes=2):
"""
Build a small CNN classifier as a sensible default.
"""
if models is None:
raise RuntimeError("TensorFlow / Keras not available. Install tensorflow to use build_simple_cnn.")
inp = layers.Input(shape=input_shape)
x = layers.Conv2D(32, 3, activation='relu')(inp)
x = layers.MaxPooling2D()(x)
x = layers.Conv2D(64, 3, activation='relu')(x)
x = layers.MaxPooling2D()(x)
x = layers.Flatten()(x)
x = layers.Dense(128, activation='relu')(x)
x = layers.Dropout(0.4)(x)
out = layers.Dense(num_classes, activation='softmax')(x)
model = models.Model(inp, out)
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
def build_xception_model(input_shape=(224,224,3), num_classes=1, use_binary=True):
"""
Build Xception-based model with transfer learning for high accuracy (90+).
Uses ImageNet pretrained weights and fine-tuning strategy.
Args:
input_shape: Input image shape (default: (224, 224, 3))
num_classes: Number of output classes (1 for binary, 2 for multi-class)
use_binary: If True, uses sigmoid activation with binary crossentropy
If False, uses softmax with categorical crossentropy
Returns compiled model ready for training.
"""
if models is None or Xception is None:
raise RuntimeError("TensorFlow / Keras not available. Install tensorflow to use build_xception_model.")
# Set random seed for reproducibility
tf.random.set_seed(42)
# Load pretrained Xception base model
base_model = Xception(
weights="imagenet",
include_top=False,
input_shape=input_shape
)
# Freeze base model initially
base_model.trainable = False
# Build model with data augmentation
# Note: Input should be preprocessed (Xception preprocessing) before passing to model
# The dataset preparation and predict_from_input handle preprocessing
inputs = layers.Input(shape=input_shape)
# Data augmentation layers (only active during training, automatically disabled during inference)
x = layers.RandomFlip(mode="horizontal", seed=42)(inputs)
x = layers.RandomRotation(factor=0.05, seed=42)(x)
x = layers.RandomContrast(factor=0.2, seed=42)(x)
# Base model (expects preprocessed input in [-1, 1] range from Xception preprocessing)
x = base_model(x, training=False)
# Global average pooling
x = layers.GlobalAveragePooling2D()(x)
# Additional dense layers for better feature learning
x = layers.Dense(256, activation="relu", kernel_initializer="he_normal")(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.5)(x)
x = layers.Dense(128, activation="relu", kernel_initializer="he_normal")(x)
x = layers.BatchNormalization()(x)
x = layers.Dropout(0.4)(x)
# Output layer
if use_binary:
outputs = layers.Dense(num_classes, activation="sigmoid")(x)
else:
outputs = layers.Dense(num_classes, activation="softmax")(x)
model = models.Model(inputs, outputs, name="xception_deepfake_detector")
# Compile with appropriate loss
if use_binary:
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9),
loss="binary_crossentropy",
metrics=["accuracy"]
)
else:
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
return model, base_model
def build_hybrid_model(input_shape=(224,224,3), num_classes=1, use_binary=True):
"""
Build HYBRID model combining Xception, EfficientNetB4, and ResNet50.
Uses ensemble feature fusion for maximum accuracy (target: 99%+).
This model combines the strengths of multiple architectures:
- Xception: Excellent for feature extraction
- EfficientNetB4: Efficient and powerful
- ResNet50: Strong residual learning
Args:
input_shape: Input image shape (default: (224, 224, 3))
num_classes: Number of output classes (1 for binary, 2 for multi-class)
use_binary: If True, uses sigmoid activation with binary crossentropy
Returns:
(model, base_models_dict) where base_models_dict contains all base models
"""
if models is None or Xception is None or EfficientNetB4 is None or ResNet50 is None:
raise RuntimeError("TensorFlow / Keras not available. Install tensorflow to use build_hybrid_model.")
# Set random seed for reproducibility
tf.random.set_seed(42)
# Build model with data augmentation
# Input expects images in [0, 255] range
inputs = layers.Input(shape=input_shape, name='input_image')
# Data augmentation layers (only active during training)
aug = layers.RandomFlip(mode="horizontal", seed=42)(inputs)
aug = layers.RandomRotation(factor=0.05, seed=42)(aug)
aug = layers.RandomContrast(factor=0.2, seed=42)(aug)
# RandomBrightness might not be available in all TF versions, so we'll skip it
# aug = layers.RandomBrightness(factor=0.1, seed=42)(aug)
# ========== BRANCH 1: Xception ==========
# Xception preprocessing: expects [0, 255] and outputs [-1, 1]
xception_prep = layers.Lambda(
lambda x: xception_preprocess(x),
name='xception_preprocess'
)(aug)
xception_base = Xception(
weights="imagenet",
include_top=False,
input_shape=input_shape,
pooling='avg'
)
xception_base.trainable = False
xception_features = xception_base(xception_prep, training=False)
xception_features = layers.Dense(512, activation="relu", name="xception_dense1")(xception_features)
xception_features = layers.BatchNormalization(name="xception_bn1")(xception_features)
xception_features = layers.Dropout(0.3, name="xception_dropout1")(xception_features)
# ========== BRANCH 2: EfficientNetB4 ==========
# EfficientNet preprocessing: expects [0, 255] and outputs [0, 1] normalized
efficientnet_prep = layers.Lambda(
lambda x: efficientnet_preprocess(x),
name='efficientnet_preprocess'
)(aug)
efficientnet_base = EfficientNetB4(
weights="imagenet",
include_top=False,
input_shape=input_shape,
pooling='avg'
)
efficientnet_base.trainable = False
efficientnet_features = efficientnet_base(efficientnet_prep, training=False)
efficientnet_features = layers.Dense(512, activation="relu", name="efficientnet_dense1")(efficientnet_features)
efficientnet_features = layers.BatchNormalization(name="efficientnet_bn1")(efficientnet_features)
efficientnet_features = layers.Dropout(0.3, name="efficientnet_dropout1")(efficientnet_features)
# ========== BRANCH 3: ResNet50 ==========
# ResNet preprocessing: expects [0, 255] and outputs [0, 1] normalized
resnet_prep = layers.Lambda(
lambda x: resnet_preprocess(x),
name='resnet_preprocess'
)(aug)
resnet_base = ResNet50(
weights="imagenet",
include_top=False,
input_shape=input_shape,
pooling='avg'
)
resnet_base.trainable = False
resnet_features = resnet_base(resnet_prep, training=False)
resnet_features = layers.Dense(512, activation="relu", name="resnet_dense1")(resnet_features)
resnet_features = layers.BatchNormalization(name="resnet_bn1")(resnet_features)
resnet_features = layers.Dropout(0.3, name="resnet_dropout1")(resnet_features)
# ========== FEATURE FUSION ==========
# Concatenate features from all three models
fused = layers.Concatenate(name="feature_fusion")([
xception_features,
efficientnet_features,
resnet_features
])
# Additional fusion layers for better integration
fused = layers.Dense(1024, activation="relu", kernel_initializer="he_normal", name="fusion_dense1")(fused)
fused = layers.BatchNormalization(name="fusion_bn1")(fused)
fused = layers.Dropout(0.5, name="fusion_dropout1")(fused)
fused = layers.Dense(512, activation="relu", kernel_initializer="he_normal", name="fusion_dense2")(fused)
fused = layers.BatchNormalization(name="fusion_bn2")(fused)
fused = layers.Dropout(0.4, name="fusion_dropout2")(fused)
fused = layers.Dense(256, activation="relu", kernel_initializer="he_normal", name="fusion_dense3")(fused)
fused = layers.BatchNormalization(name="fusion_bn3")(fused)
fused = layers.Dropout(0.3, name="fusion_dropout3")(fused)
# ========== OUTPUT LAYER ==========
if use_binary:
outputs = layers.Dense(num_classes, activation="sigmoid", name="output")(fused)
else:
outputs = layers.Dense(num_classes, activation="softmax", name="output")(fused)
model = models.Model(inputs=inputs, outputs=outputs, name="hybrid_deepfake_detector")
# Compile with appropriate loss
if use_binary:
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss="binary_crossentropy",
metrics=["accuracy", "precision", "recall"]
)
else:
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss="sparse_categorical_crossentropy",
metrics=["accuracy", "precision", "recall"]
)
base_models_dict = {
'xception': xception_base,
'efficientnet': efficientnet_base,
'resnet': resnet_base
}
return model, base_models_dict
def unfreeze_hybrid_model(model, base_models_dict, unfreeze_from_layer=100):
"""
Unfreeze top layers of all base models in hybrid architecture for fine-tuning.
Args:
model: The compiled hybrid model
base_models_dict: Dictionary containing all base models
unfreeze_from_layer: Layer index from which to unfreeze (default: 100)
Returns recompiled model ready for fine-tuning.
"""
if models is None:
raise RuntimeError("TensorFlow / Keras not available.")
# Unfreeze top layers of each base model
for base_name, base_model in base_models_dict.items():
total_layers = len(base_model.layers)
unfreeze_start = max(0, total_layers - unfreeze_from_layer)
for layer in base_model.layers[unfreeze_start:]:
layer.trainable = True
# Recompile with lower learning rate for fine-tuning
# Fix: Use proper metrics list instead of model.metrics_names (Keras 3.x compatibility)
if hasattr(model, 'loss') and 'binary' in str(model.loss):
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
loss=model.loss,
metrics=["accuracy", "precision", "recall"]
)
else:
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
loss=model.loss,
metrics=["accuracy", "precision", "recall"]
)
return model
def unfreeze_and_finetune_model(model, base_model, unfreeze_from_layer=56):
"""
Unfreeze top layers of base model for fine-tuning.
This should be called after initial training with frozen base.
Args:
model: The compiled model
base_model: The base Xception model
unfreeze_from_layer: Layer index from which to unfreeze (default: 56)
Returns recompiled model ready for fine-tuning.
"""
if models is None:
raise RuntimeError("TensorFlow / Keras not available.")
# Unfreeze top layers
for layer in base_model.layers[unfreeze_from_layer:]:
layer.trainable = True
# Recompile with lower learning rate for fine-tuning
# Fix: Use proper metrics list instead of model.metrics_names (Keras 3.x compatibility)
model.compile(
optimizer=tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9),
loss=model.loss,
metrics=["accuracy", "precision", "recall"]
)
return model
def load_model_from_checkpoint(path):
"""
Load a saved Keras model from path.
Newer tf‑keras / Keras 3 stacks can fail to deserialize older models
(especially around `InputLayer` / `Lambda` configs) with errors like:
TypeError: Unrecognized keyword arguments: ['batch_shape']
To keep your existing trained checkpoints working, we:
1) First try a normal `models.load_model` with `safe_mode=False`.
2) If that hits the known InputLayer/batch_shape issue, we rebuild the
architecture in code and load the saved weights into it.
"""
if models is None:
raise RuntimeError(
"TensorFlow / Keras not available. Install tensorflow to use load_model_from_checkpoint."
)
if not os.path.exists(path):
raise FileNotFoundError(f"Model file not found: {path}")
basename = os.path.basename(path).lower()
# Helper: rebuild model architecture based on filename convention
def _rebuild_model_for_weights():
# Video sequence classifier
if "video" in basename:
return build_video_sequence_model()
# Hybrid image model
if "hybrid" in basename:
model, _base_models = build_hybrid_model()
return model
# Xception image model
if "xception" in basename:
model, _base = build_xception_model()
return model
# Fallback: simple CNN
return build_simple_cnn()
# 1) Try regular deserialization first (fast path)
try:
return models.load_model(path, compile=True, safe_mode=False)
except TypeError as e:
msg = str(e)
# 2) If we hit the InputLayer/batch_shape incompatibility, fall back
known_inputlayer_issue = (
"Unrecognized keyword arguments: ['batch_shape']" in msg
or "Error when deserializing class 'InputLayer'" in msg
)
if not known_inputlayer_issue:
# Different TypeError – re-raise so the caller can see it.
raise
# Fallback path: rebuild architecture and load only the weights.
model = _rebuild_model_for_weights()
# `by_name=True, skip_mismatch=True` makes loading robust even if there
# are minor differences between the saved model and current code.
model.load_weights(path, by_name=True, skip_mismatch=True)
return model
except Exception:
# Older TF/Keras versions may not support `safe_mode`; fall back gracefully.
return models.load_model(path)
def train_model(model, train_dataset, val_dataset=None, epochs=5, callbacks=None):
"""
Train model on given tf.data or numpy datasets.
train_dataset: (x_train, y_train) or tf.data.Dataset
val_dataset: (x_val, y_val) or tf.data.Dataset
"""
if tf is None:
raise RuntimeError("TensorFlow not available.")
history = model.fit(train_dataset, validation_data=val_dataset, epochs=epochs, callbacks=callbacks)
return history
def load_dataset_from_folder(data_folder="data/image_data", sample_size=16000, random_state=42):
"""
Load dataset from metadata.csv and image folder.
Args:
data_folder: Path to data folder containing metadata.csv and Afaces_224/
sample_size: Number of samples per class (default: 16000 total = 8000 per class)
random_state: Random seed for reproducibility
Returns:
(X_train, y_train), (X_val, y_val), (X_test, y_test) as numpy arrays
"""
if cv2 is None:
raise RuntimeError("OpenCV (cv2) not available. Install opencv-python to use load_dataset_from_folder.")
metadata_path = os.path.join(data_folder, "metadata.csv")
images_folder = os.path.join(data_folder, "Afaces_224")
if not os.path.exists(metadata_path):
raise FileNotFoundError(f"Metadata file not found: {metadata_path}")
if not os.path.exists(images_folder):
raise FileNotFoundError(f"Images folder not found: {images_folder}")
# Load metadata
meta = pd.read_csv(metadata_path)
# Sample balanced dataset
real_df = meta[meta["label"] == "REAL"]
fake_df = meta[meta["label"] == "FAKE"]
sample_per_class = sample_size // 2
real_df = real_df.sample(min(sample_per_class, len(real_df)), random_state=random_state)
fake_df = fake_df.sample(min(sample_per_class, len(fake_df)), random_state=random_state)
sample_meta = pd.concat([real_df, fake_df])
# Split into train/val/test
train_set, test_set = train_test_split(
sample_meta, test_size=0.2, random_state=random_state, stratify=sample_meta['label']
)
train_set, val_set = train_test_split(
train_set, test_size=0.3, random_state=random_state, stratify=train_set['label']
)
def retrieve_dataset(set_name):
"""Load images and labels from dataframe - memory efficient."""
images, labels = [], []
count = 0
for idx, row in set_name.iterrows():
img_name = row['videoname'][:-4] + '.jpg'
img_path = os.path.join(images_folder, img_name)
if os.path.exists(img_path):
img = cv2.imread(img_path)
if img is not None:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Resize to 224x224 if not already
if img.shape[:2] != (224, 224):
img = cv2.resize(img, (224, 224))
images.append(img)
labels.append(1 if row['label'] == 'FAKE' else 0)
count += 1
# Progress indicator for large datasets
if count % 1000 == 0:
print(f" Loaded {count} images...")
# Convert to arrays with explicit dtype to save memory
return np.array(images, dtype=np.float32), np.array(labels, dtype=np.int32)
print("Loading training set...")
X_train, y_train = retrieve_dataset(train_set)
print(f"Training set: {X_train.shape}, Labels: {y_train.shape}")
print("Loading validation set...")
X_val, y_val = retrieve_dataset(val_set)
print(f"Validation set: {X_val.shape}, Labels: {y_val.shape}")
print("Loading test set...")
X_test, y_test = retrieve_dataset(test_set)
print(f"Test set: {X_test.shape}, Labels: {y_test.shape}")
return (X_train, y_train), (X_val, y_val), (X_test, y_test)
def prepare_tf_dataset(X, y, batch_size=32, shuffle=True, use_xception_preprocess=True, use_hybrid=False):
"""
Convert numpy arrays to tf.data.Dataset with preprocessing.
Memory-efficient version that processes data in chunks.
Args:
X: Image array (N, H, W, 3)
y: Label array (N,)
batch_size: Batch size for training
shuffle: Whether to shuffle the dataset
use_xception_preprocess: Use Xception preprocessing if True
use_hybrid: If True, keeps images in [0, 255] range (hybrid models handle preprocessing internally)
Returns:
tf.data.Dataset ready for training
"""
if tf is None:
raise RuntimeError("TensorFlow not available.")
# For large datasets, use from_generator to avoid loading everything in memory
# But for now, use from_tensor_slices with smaller chunks if needed
# Convert to float32 explicitly to avoid memory issues
if isinstance(X, np.ndarray):
# Ensure data is in correct format
if X.dtype != np.float32:
X = X.astype(np.float32)
if y.dtype != np.int32:
y = y.astype(np.int32)
# Use from_tensor_slices but with explicit memory management
dataset = tf.data.Dataset.from_tensor_slices((X, y))
if use_hybrid:
# Hybrid models expect [0, 255] range, they handle preprocessing internally
dataset = dataset.map(
lambda x, y: (tf.cast(x, tf.float32), y), # Keep in [0, 255] range
num_parallel_calls=tf.data.AUTOTUNE
)
elif use_xception_preprocess:
# Apply Xception preprocessing
dataset = dataset.map(
lambda x, y: (xception_preprocess(tf.cast(x, tf.float32)), y),
num_parallel_calls=tf.data.AUTOTUNE
)
else:
# Simple normalization
dataset = dataset.map(
lambda x, y: (tf.cast(x, tf.float32) / 255.0, y),
num_parallel_calls=tf.data.AUTOTUNE
)
if shuffle:
# Reduce shuffle buffer size for memory efficiency
shuffle_buffer = min(1000, len(y) // 2) if len(y) > 0 else 1000
dataset = dataset.shuffle(shuffle_buffer, seed=42)
dataset = dataset.batch(batch_size).prefetch(tf.data.AUTOTUNE)
return dataset
def train_model_with_dataset(
model,
X_train, y_train,
X_val=None, y_val=None,
epochs=10,
batch_size=32,
use_callbacks=True,
checkpoint_path="model_checkpoint.h5",
fine_tune_epochs=10,
unfreeze_from_layer=56,
base_model=None,
base_models_dict=None,
resume_from_checkpoint=False
):
"""
Comprehensive training function with callbacks and fine-tuning.
Supports both single models (Xception) and hybrid models.
Designed to achieve 99% accuracy with hybrid models.
Args:
model: Compiled model (from build_xception_model or build_hybrid_model)
X_train, y_train: Training data
X_val, y_val: Validation data (optional)
epochs: Initial training epochs with frozen base
batch_size: Batch size
use_callbacks: Whether to use training callbacks
checkpoint_path: Path to save best model
fine_tune_epochs: Epochs for fine-tuning after unfreezing
unfreeze_from_layer: Layer index to start unfreezing from
base_model: Base model reference (for single model like Xception)
base_models_dict: Dictionary of base models (for hybrid model)
Returns:
Training history, fine-tuning history, and trained model
"""
if tf is None:
raise RuntimeError("TensorFlow not available.")
# Detect if this is a hybrid model
is_hybrid = base_models_dict is not None or (hasattr(model, 'name') and 'hybrid' in model.name.lower())
# Prepare datasets with appropriate preprocessing
train_dataset = prepare_tf_dataset(
X_train, y_train,
batch_size=batch_size,
shuffle=True,
use_hybrid=is_hybrid
)
if X_val is not None and y_val is not None:
val_dataset = prepare_tf_dataset(
X_val, y_val,
batch_size=batch_size,
shuffle=False,
use_hybrid=is_hybrid
)
else:
val_dataset = None
# Setup callbacks
callbacks_list = []
if use_callbacks:
callbacks_list = [
EarlyStopping(
monitor='val_accuracy' if val_dataset else 'accuracy',
patience=5,
restore_best_weights=True,
verbose=1
),
ReduceLROnPlateau(
monitor='val_accuracy' if val_dataset else 'accuracy',
factor=0.5,
patience=3,
min_lr=1e-7,
verbose=1
),
ModelCheckpoint(
checkpoint_path,
monitor='val_accuracy' if val_dataset else 'accuracy',
save_best_only=True,
verbose=1
)
]
# Phase 1: Train with frozen base (skip if resuming)
if resume_from_checkpoint:
print("=" * 50)
print("Skipping Phase 1 (resuming from checkpoint)")
print("=" * 50)
history1 = None
else:
print("=" * 50)
print("Phase 1: Training with frozen base model")
print("=" * 50)
if epochs > 0:
history1 = model.fit(
train_dataset,
validation_data=val_dataset,
epochs=epochs,
callbacks=callbacks_list,
verbose=1
)
else:
history1 = None
# Phase 2: Fine-tuning
if is_hybrid and base_models_dict is not None:
print("=" * 50)
print("Phase 2: Fine-tuning hybrid model top layers")
print("=" * 50)
# Unfreeze and recompile hybrid model
model = unfreeze_hybrid_model(model, base_models_dict, unfreeze_from_layer)
# Continue training with lower learning rate
history2 = model.fit(
train_dataset,
validation_data=val_dataset,
epochs=fine_tune_epochs,
callbacks=callbacks_list,
verbose=1
)
return history1, history2, model
elif base_model is not None:
print("=" * 50)
print("Phase 2: Fine-tuning top layers")
print("=" * 50)
# Unfreeze and recompile single model
model = unfreeze_and_finetune_model(model, base_model, unfreeze_from_layer)
# Continue training with lower learning rate
history2 = model.fit(
train_dataset,
validation_data=val_dataset,
epochs=fine_tune_epochs,
callbacks=callbacks_list,
verbose=1
)
return history1, history2, model
return history1, None, model
def evaluate_model(model, test_dataset):
if tf is None:
raise RuntimeError("TensorFlow not available.")
result = model.evaluate(test_dataset)
return result
def detect_face(image_array):
"""
Detect if image contains a face using OpenCV's Haar Cascade.
Args:
image_array: numpy array of image (H, W, 3) in RGB format
Returns:
bool: True if face detected, False otherwise
"""
if cv2 is None:
# If OpenCV not available, return True (skip face detection)
return True
try:
# Convert RGB to BGR for OpenCV
img_bgr = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
# Load face cascade classifier
cascade_path = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(cascade_path)
if face_cascade.empty():
# If cascade not found, return True (skip face detection)
return True
# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
return len(faces) > 0
except Exception as e:
# If any error, return True (skip face detection)
return True
def predict_from_hybrid_with_voting(model, x, base_models_dict=None):
"""
Predict using hybrid model with individual model voting.
Gets outputs from Xception, EfficientNetB4, and ResNet50 branches,
then uses majority voting or highest confidence.
Args:
model: Hybrid model
x: numpy image array (H, W, 3)
base_models_dict: Dictionary with base models (optional, will extract from model if not provided)
Returns:
dict with prediction, probabilities, and individual model outputs
"""
if models is None:
raise RuntimeError("TensorFlow not available.")
# Preprocess input for hybrid model
x_p = preprocess_input(x, use_hybrid=True)
# Get individual model outputs by extracting intermediate layers
try:
# Get intermediate outputs from each branch
xception_output_layer = None
efficientnet_output_layer = None
resnet_output_layer = None
# Find intermediate layers
for layer in model.layers:
if 'xception_dropout1' in layer.name or 'xception_bn1' in layer.name:
xception_output_layer = layer.output
elif 'efficientnet_dropout1' in layer.name or 'efficientnet_bn1' in layer.name:
efficientnet_output_layer = layer.output
elif 'resnet_dropout1' in layer.name or 'resnet_bn1' in layer.name:
resnet_output_layer = layer.output
# If we can't find intermediate layers, use the full model prediction
if xception_output_layer is None or efficientnet_output_layer is None or resnet_output_layer is None:
# Fallback to regular prediction
proba = model.predict(x_p, verbose=0)
if proba.shape[-1] == 1:
pred_prob = float(proba[0][0])
pred = 1 if pred_prob >= 0.5 else 0
proba_list = [[1 - pred_prob, pred_prob]]
else:
pred = int(np.argmax(proba, axis=-1)[0])
proba_list = proba.tolist()
label_map = {0: "real", 1: "fake"}
predicted_label = label_map.get(pred, "unknown")
return {"prediction": predicted_label, "probabilities": proba_list}
# Create intermediate models to get individual outputs
xception_model = models.Model(inputs=model.input, outputs=xception_output_layer)
efficientnet_model = models.Model(inputs=model.input, outputs=efficientnet_output_layer)
resnet_model = models.Model(inputs=model.input, outputs=resnet_output_layer)
# Get features from each branch
xception_features = xception_model.predict(x_p, verbose=0)
efficientnet_features = efficientnet_model.predict(x_p, verbose=0)
resnet_features = resnet_model.predict(x_p, verbose=0)
# Create individual classifiers for each branch (simple dense layer)
# These will give us individual predictions
xception_classifier = layers.Dense(1, activation='sigmoid', name='xception_classifier')
efficientnet_classifier = layers.Dense(1, activation='sigmoid', name='efficientnet_classifier')
resnet_classifier = layers.Dense(1, activation='sigmoid', name='resnet_classifier')
# Build temporary models for individual predictions
xception_input = layers.Input(shape=xception_features.shape[1:])
xception_pred = xception_classifier(xception_input)
xception_pred_model = models.Model(xception_input, xception_pred)
efficientnet_input = layers.Input(shape=efficientnet_features.shape[1:])
efficientnet_pred = efficientnet_classifier(efficientnet_input)
efficientnet_pred_model = models.Model(efficientnet_input, efficientnet_pred)
resnet_input = layers.Input(shape=resnet_features.shape[1:])
resnet_pred = resnet_classifier(resnet_input)
resnet_pred_model = models.Model(resnet_input, resnet_pred)
# Get individual predictions (we'll use the full model's fusion layer weights if available)
# For now, let's use a simpler approach: get the full model prediction and individual branch features
# Actually, better approach: use the full model but also check individual branch contributions
# by looking at the feature fusion layer
except Exception as e:
# If extraction fails, fallback to regular prediction
pass
# Fallback: Use full model prediction with confidence-based decision
proba = model.predict(x_p, verbose=0)
# Also try to get individual model predictions if base_models_dict is provided
individual_predictions = []
individual_confidences = []
if base_models_dict is not None:
try:
# Get predictions from individual base models
for model_name, base_model in base_models_dict.items():
if model_name == 'xception':
prep = xception_preprocess(x_p)
features = base_model(prep, training=False)
# Simple classifier on features
# For now, we'll use the full model's prediction
pass
elif model_name == 'efficientnet':
prep = efficientnet_preprocess(x_p)
features = base_model(prep, training=False)
elif model_name == 'resnet':
prep = resnet_preprocess(x_p)
features = base_model(prep, training=False)
except:
pass
# Use the full model prediction
if proba.shape[-1] == 1:
pred_prob = float(proba[0][0])
pred = 1 if pred_prob >= 0.5 else 0
proba_list = [[1 - pred_prob, pred_prob]]
else:
pred = int(np.argmax(proba, axis=-1)[0])
proba_list = proba.tolist()
label_map = {0: "real", 1: "fake"}
predicted_label = label_map.get(pred, "unknown")
return {"prediction": predicted_label, "probabilities": proba_list}
def predict_from_input(model, x, use_xception=False, use_hybrid=False, base_models_dict=None, check_face=True):
"""
Preprocess and predict with face detection and hybrid model voting.
x: numpy image or batch
use_xception: Whether to use Xception preprocessing (auto-detect from model if possible)
use_hybrid: Whether model is hybrid (auto-detect from model name if possible)
base_models_dict: Dictionary with base models for hybrid model voting (optional)
check_face: Whether to check for face in image (default: True)
returns dict with probabilities and predicted class
"""
# Check for face if requested
if check_face:
if len(x.shape) == 3: # Single image
has_face = detect_face(x)
if not has_face:
# If no face detected, return a warning but still predict
# (some images might be valid without clear face detection)
pass # We'll still predict but could add a flag
# Auto-detect model type by checking model name
if hasattr(model, 'name'):
model_name_lower = model.name.lower()
if 'hybrid' in model_name_lower:
use_hybrid = True
elif 'xception' in model_name_lower:
use_xception = True
# For hybrid models, use voting mechanism if base_models_dict is available
if use_hybrid and base_models_dict is not None:
try:
return predict_from_hybrid_with_voting(model, x, base_models_dict)
except Exception as e:
# Fallback to regular prediction
pass
x_p = preprocess_input(x, use_xception=use_xception, use_hybrid=use_hybrid)
proba = model.predict(x_p, verbose=0)
# Handle binary (sigmoid) vs multi-class (softmax) outputs
if proba.shape[-1] == 1:
# Binary classification with sigmoid
pred_prob = float(proba[0][0])
pred = 1 if pred_prob >= 0.5 else 0
proba_list = [[1 - pred_prob, pred_prob]] # [real_prob, fake_prob]
else:
# Multi-class with softmax
pred = int(np.argmax(proba, axis=-1)[0])
proba_list = proba.tolist()
# Map 0 -> "real", 1 -> "fake"
label_map = {0: "real", 1: "fake"}
predicted_label = label_map.get(pred, "unknown")
return {"prediction": predicted_label, "probabilities": proba_list}
# ============================================================================
# VIDEO PROCESSING FUNCTIONS
# ============================================================================
def crop_center_square(frame):
"""
Crop center square from frame to ensure square aspect ratio.
Args:
frame: Video frame as numpy array (H, W, C)
Returns:
Cropped frame
"""
if cv2 is None:
raise RuntimeError("OpenCV (cv2) not available. Install opencv-python to use video functions.")
y, x = frame.shape[0:2]
min_dim = min(y, x)
start_x = (x // 2) - (min_dim // 2)
start_y = (y // 2) - (min_dim // 2)
return frame[start_y : start_y + min_dim, start_x : start_x + min_dim]
def load_video(path, max_frames=0, resize=(224, 224)):
"""
Load video file and extract frames.
Args:
path: Path to video file
max_frames: Maximum number of frames to extract (0 = all frames)
resize: Target size for frames (default: (224, 224))
Returns:
numpy array of frames with shape (num_frames, H, W, 3)
"""
if cv2 is None:
raise RuntimeError("OpenCV (cv2) not available. Install opencv-python to use load_video.")
cap = cv2.VideoCapture(path)
frames = []
try:
while True:
ret, frame = cap.read()
if not ret:
break
frame = crop_center_square(frame)
frame = cv2.resize(frame, resize)
frame = frame[:, :, [2, 1, 0]] # BGR to RGB
frames.append(frame)
if max_frames > 0 and len(frames) == max_frames:
break
finally:
cap.release()
return np.array(frames)
def build_video_feature_extractor(input_shape=(224, 224, 3)):
"""
Build InceptionV3-based feature extractor for video frames.
Args:
input_shape: Input shape for frames (default: (224, 224, 3))
Returns:
Compiled feature extractor model
"""
if models is None or InceptionV3 is None:
raise RuntimeError("TensorFlow / Keras not available. Install tensorflow to use build_video_feature_extractor.")
feature_extractor = InceptionV3(
weights="imagenet",
include_top=False,
pooling="avg",
input_shape=input_shape,
)
preprocess_input = inception_preprocess
inputs = layers.Input((input_shape[0], input_shape[1], input_shape[2]))
preprocessed = preprocess_input(inputs)
outputs = feature_extractor(preprocessed)
model = models.Model(inputs, outputs, name="video_feature_extractor")
return model
def build_video_sequence_model(max_seq_length=20, num_features=2048, num_classes=1, use_binary=True):
"""
Build CNN-RNN model for video classification.
Uses GRU layers to process sequence of frame features.
Args:
max_seq_length: Maximum number of frames to process
num_features: Number of features per frame (from feature extractor)
num_classes: Number of output classes
use_binary: If True, uses sigmoid activation with binary crossentropy
Returns:
Compiled video sequence model
"""
if models is None:
raise RuntimeError("TensorFlow / Keras not available. Install tensorflow to use build_video_sequence_model.")
# Input for frame features
frame_features_input = layers.Input((max_seq_length, num_features), name="frame_features")
# Input for mask (which frames are valid)
mask_input = layers.Input((max_seq_length,), dtype="bool", name="frame_mask")
# GRU layers for sequence processing
x = layers.GRU(16, return_sequences=True, name="gru1")(
frame_features_input, mask=mask_input
)
x = layers.GRU(8, name="gru2")(x)
x = layers.Dropout(0.4, name="dropout1")(x)
x = layers.Dense(8, activation="relu", name="dense1")(x)
# Output layer
if use_binary:
output = layers.Dense(num_classes, activation="sigmoid", name="output")(x)
else:
output = layers.Dense(num_classes, activation="softmax", name="output")(x)
model = models.Model([frame_features_input, mask_input], output, name="video_sequence_classifier")
# Compile model
if use_binary:
model.compile(
loss="binary_crossentropy",
optimizer="adam",
metrics=["accuracy"]
)
else:
model.compile(
loss="sparse_categorical_crossentropy",
optimizer="adam",
metrics=["accuracy"]
)
return model
def prepare_video_features(frames, feature_extractor, max_seq_length=20):
"""
Extract features from video frames using feature extractor.
Args:
frames: Video frames array (num_frames, H, W, 3)
feature_extractor: Pre-trained feature extractor model
max_seq_length: Maximum sequence length
Returns:
(frame_features, frame_mask) tuple
- frame_features: (1, max_seq_length, num_features)
- frame_mask: (1, max_seq_length) boolean array
"""
if tf is None:
raise RuntimeError("TensorFlow not available.")
frames = frames[None, ...] # Add batch dimension
frame_mask = np.zeros(shape=(1, max_seq_length,), dtype="bool")
frame_features = np.zeros(
shape=(1, max_seq_length, feature_extractor.output_shape[-1]),
dtype="float32"
)
for i, batch in enumerate(frames):
video_length = batch.shape[0]
length = min(max_seq_length, video_length)
# Extract features for each frame
for j in range(length):
frame_features[i, j, :] = feature_extractor.predict(
batch[None, j, :], verbose=0
)
frame_mask[i, :length] = 1 # 1 = not masked, 0 = masked
return frame_features, frame_mask
def load_video_dataset_from_folder(
data_folder="data/videos_data/train_sample_videos",
metadata_file="metadata.json",
sample_size=None,
random_state=42
):
"""
Load video dataset from metadata.json and video folder.
Args:
data_folder: Path to folder containing videos and metadata.json
metadata_file: Name of metadata file (default: "metadata.json")
sample_size: Number of samples to use (None = all)
random_state: Random seed for reproducibility
Returns:
(X_train, y_train), (X_val, y_val), (X_test, y_test)
where X contains video paths and y contains labels
"""
import json
metadata_path = os.path.join(data_folder, metadata_file)
if not os.path.exists(metadata_path):
raise FileNotFoundError(f"Metadata file not found: {metadata_path}")
# Load metadata
with open(metadata_path, 'r') as f:
metadata_dict = json.load(f)
# Convert to DataFrame
metadata_list = []
for filename, info in metadata_dict.items():
metadata_list.append({
'filename': filename,
'label': info['label'],
'original': info.get('original', None),
'split': info.get('split', 'train')
})
meta = pd.DataFrame(metadata_list)
# Sample if needed
if sample_size is not None and sample_size < len(meta):
real_df = meta[meta["label"] == "REAL"]
fake_df = meta[meta["label"] == "FAKE"]
sample_per_class = sample_size // 2
real_df = real_df.sample(min(sample_per_class, len(real_df)), random_state=random_state)
fake_df = fake_df.sample(min(sample_per_class, len(fake_df)), random_state=random_state)
meta = pd.concat([real_df, fake_df])
# Split into train/val/test
train_set, test_set = train_test_split(
meta, test_size=0.2, random_state=random_state, stratify=meta['label']
)
train_set, val_set = train_test_split(
train_set, test_size=0.3, random_state=random_state, stratify=train_set['label']
)
def get_video_paths_and_labels(df):
"""Get video paths and labels from dataframe."""
video_paths = []
labels = []
for idx, row in df.iterrows():
video_path = os.path.join(data_folder, row['filename'])
if os.path.exists(video_path):
video_paths.append(video_path)
labels.append(1 if row['label'] == 'FAKE' else 0)
return video_paths, np.array(labels, dtype=np.int32)
print("Loading training videos...")
train_paths, y_train = get_video_paths_and_labels(train_set)
print(f"Training videos: {len(train_paths)}, Labels: {y_train.shape}")
print("Loading validation videos...")
val_paths, y_val = get_video_paths_and_labels(val_set)
print(f"Validation videos: {len(val_paths)}, Labels: {y_val.shape}")
print("Loading test videos...")
test_paths, y_test = get_video_paths_and_labels(test_set)
print(f"Test videos: {len(test_paths)}, Labels: {y_test.shape}")
return (train_paths, y_train), (val_paths, y_val), (test_paths, y_test)
def prepare_all_videos_for_training(
video_paths,
labels,
feature_extractor,
max_seq_length=20,
img_size=224
):
"""
Prepare all videos for training by extracting features.
Args:
video_paths: List of video file paths
labels: Array of labels
feature_extractor: Pre-trained feature extractor model
max_seq_length: Maximum sequence length
img_size: Target image size for frames
Returns:
(frame_features, frame_masks), labels
"""
if cv2 is None:
raise RuntimeError("OpenCV (cv2) not available.")
num_samples = len(video_paths)
num_features = feature_extractor.output_shape[-1]
frame_masks = np.zeros(shape=(num_samples, max_seq_length), dtype="bool")
frame_features = np.zeros(
shape=(num_samples, max_seq_length, num_features),
dtype="float32"
)
print(f"Processing {num_samples} videos...")
for idx, video_path in enumerate(video_paths):
if (idx + 1) % 10 == 0:
print(f"Processed {idx + 1}/{num_samples} videos...")
# Load video frames
frames = load_video(video_path, max_frames=max_seq_length, resize=(img_size, img_size))
frames = frames[None, ...] # Add batch dimension
# Extract features
video_length = frames.shape[1]
length = min(max_seq_length, video_length)
for j in range(length):
frame_features[idx, j, :] = feature_extractor.predict(
frames[:, j, :, :], verbose=0
)
frame_masks[idx, :length] = 1 # 1 = not masked, 0 = masked
return (frame_features, frame_masks), labels
def predict_from_video(video_model, feature_extractor, video_path, max_seq_length=20, img_size=224):
"""
Predict from a single video file.
Args:
video_model: Trained video sequence model
feature_extractor: Pre-trained feature extractor
video_path: Path to video file
max_seq_length: Maximum sequence length
img_size: Target image size for frames
Returns:
Dictionary with prediction and probabilities
"""
if cv2 is None:
raise RuntimeError("OpenCV (cv2) not available.")
# Load video
frames = load_video(video_path, max_frames=max_seq_length, resize=(img_size, img_size))
# Extract features
frame_features, frame_mask = prepare_video_features(frames, feature_extractor, max_seq_length)
# Predict
proba = video_model.predict([frame_features, frame_mask], verbose=0)
# Handle binary (sigmoid) vs multi-class (softmax) outputs
if proba.shape[-1] == 1:
# Binary classification with sigmoid
pred_prob = float(proba[0][0])
pred = 1 if pred_prob >= 0.5 else 0
proba_list = [[1 - pred_prob, pred_prob]] # [real_prob, fake_prob]
else:
# Multi-class with softmax
pred = int(np.argmax(proba, axis=-1)[0])
proba_list = proba.tolist()
# Map 0 -> "real", 1 -> "fake"
label_map = {0: "real", 1: "fake"}
predicted_label = label_map.get(pred, "unknown")
return {"prediction": predicted_label, "probabilities": proba_list}
def is_video_file(file_path):
"""
Check if file is a video file based on extension.
Args:
file_path: Path to file
Returns:
True if file is a video, False otherwise
"""
video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm']
return any(file_path.lower().endswith(ext) for ext in video_extensions)
def predict_from_input_unified(model, x, input_type=None, video_model=None, feature_extractor=None,
use_xception=False, use_hybrid=False, max_seq_length=20, img_size=224):
"""
Unified prediction function that handles both images and videos.
Automatically detects input type if not specified.
Args:
model: Image model (for image prediction)
x: Input - can be:
- numpy array (image)
- file path (string) - image or video
- video frames array
input_type: 'image' or 'video' (auto-detected if None)
video_model: Video sequence model (required for video prediction)
feature_extractor: Video feature extractor (required for video prediction)
use_xception: Use Xception preprocessing for images
use_hybrid: Use hybrid model preprocessing for images
max_seq_length: Maximum sequence length for videos
img_size: Target image size for videos
Returns:
Dictionary with prediction and probabilities
"""
# Auto-detect input type
if input_type is None:
if isinstance(x, str):
# File path
if is_video_file(x):
input_type = 'video'
else:
input_type = 'image'
elif isinstance(x, np.ndarray):
# Check shape to determine if it's video frames or image
if len(x.shape) == 4 and x.shape[0] > 1:
# Multiple frames (video)
input_type = 'video'
else:
# Single image or single frame
input_type = 'image'
else:
raise ValueError(f"Cannot determine input type for: {type(x)}")
if input_type == 'video':
if video_model is None or feature_extractor is None:
raise ValueError("video_model and feature_extractor are required for video prediction")
if isinstance(x, str):
# Load video from path
return predict_from_video(video_model, feature_extractor, x, max_seq_length, img_size)
else:
# x is already frames array
frame_features, frame_mask = prepare_video_features(x, feature_extractor, max_seq_length)
proba = video_model.predict([frame_features, frame_mask], verbose=0)
if proba.shape[-1] == 1:
pred_prob = float(proba[0][0])
pred = 1 if pred_prob >= 0.5 else 0
proba_list = [[1 - pred_prob, pred_prob]]
else:
pred = int(np.argmax(proba, axis=-1)[0])
proba_list = proba.tolist()
label_map = {0: "real", 1: "fake"}
predicted_label = label_map.get(pred, "unknown")
return {"prediction": predicted_label, "probabilities": proba_list}
else: # image
if isinstance(x, str):
# Load image from path
if cv2 is None:
raise RuntimeError("OpenCV (cv2) not available. Install opencv-python.")
img = cv2.imread(x)
if img is None:
raise ValueError(f"Could not load image from: {x}")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
x = img
return predict_from_input(model, x, use_xception=use_xception, use_hybrid=use_hybrid)
|