Spaces:
Runtime error
Runtime error
File size: 11,598 Bytes
e0c75d6 | 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 | import os
import argparse
import json
from time import perf_counter
from datetime import datetime
from model.pred_func import *
from model.config import load_config
config = load_config()
def vids(
ed_weight, vae_weight, root_dir="sample_prediction_data", dataset=None, num_frames=15, net=None, fp16=False
):
result = set_result()
r = 0
f = 0
count = 0
model = load_genconvit(config, net, ed_weight, vae_weight, fp16)
for filename in os.listdir(root_dir):
curr_vid = os.path.join(root_dir, filename)
try:
is_vid_folder = is_video_folder(curr_vid)
if is_video(curr_vid) or is_vid_folder:
result, accuracy, count, pred = predict(
curr_vid,
model,
fp16,
result,
num_frames,
net,
"uncategorized",
count,
vid_folder=is_vid_folder
)
f, r = (f + 1, r) if "FAKE" == real_or_fake(pred[0]) else (f, r + 1)
print(
f"Prediction: {pred[1]} {real_or_fake(pred[0])} \t\tFake: {f} Real: {r}"
)
else:
print(f"Invalid video file: {curr_vid}. Please provide a valid video file.")
except Exception as e:
print(f"An error occurred: {str(e)}")
return result
def faceforensics(
ed_weight, vae_weight, root_dir="FaceForensics\\data", dataset=None, num_frames=15, net=None, fp16=False
):
vid_type = ["original_sequences", "manipulated_sequences"]
result = set_result()
result["video"]["compression"] = []
ffdirs = [
"DeepFakeDetection",
"Deepfakes",
"Face2Face",
"FaceSwap",
"NeuralTextures",
]
# load files not used in the training set, the files are appended with compression type, _c23 or _c40
with open(os.path.join("json_file", "ff_file_list.json")) as j_file:
ff_file = list(json.load(j_file))
count = 0
accuracy = 0
model = load_genconvit(config, net, ed_weight, vae_weight, fp16)
for v_t in vid_type:
for dirpath, dirnames, filenames in os.walk(os.path.join(root_dir, v_t)):
klass = next(
filter(lambda x: x in dirpath.split(os.path.sep), ffdirs),
"original",
)
label = "REAL" if klass == "original" else "FAKE"
for filename in filenames:
try:
if filename in ff_file:
curr_vid = os.path.join(dirpath, filename)
compression = "c23" if "c23" in curr_vid else "c40"
if is_video(curr_vid):
result, accuracy, count, _ = predict(
curr_vid,
model,
fp16,
result,
num_frames,
net,
klass,
count,
accuracy,
label,
compression,
)
else:
print(f"Invalid video file: {curr_vid}. Please provide a valid video file.")
except Exception as e:
print(f"An error occurred: {str(e)}")
return result
def timit(ed_weight, vae_weight, root_dir="DeepfakeTIMIT", dataset=None, num_frames=15, net=None, fp16=False):
keywords = ["higher_quality", "lower_quality"]
result = set_result()
model = load_genconvit(config, net, ed_weight, vae_weight, fp16)
count = 0
accuracy = 0
i = 0
for keyword in keywords:
keyword_folder_path = os.path.join(root_dir, keyword)
for subfolder_name in os.listdir(keyword_folder_path):
subfolder_path = os.path.join(keyword_folder_path, subfolder_name)
if os.path.isdir(subfolder_path):
# Loop through the AVI files in the subfolder
for filename in os.listdir(subfolder_path):
if filename.endswith(".avi"):
curr_vid = os.path.join(subfolder_path, filename)
try:
if is_video(curr_vid):
result, accuracy, count, _ = predict(
curr_vid,
model,
fp16,
result,
num_frames,
net,
"DeepfakeTIMIT",
count,
accuracy,
"FAKE",
)
else:
print(f"Invalid video file: {curr_vid}. Please provide a valid video file.")
except Exception as e:
print(f"An error occurred: {str(e)}")
return result
def dfdc(
ed_weight,
vae_weight,
root_dir="deepfake-detection-challenge\\train_sample_videos",
dataset=None,
num_frames=15,
net=None,
fp16=False,
):
result = set_result()
if os.path.isfile(os.path.join("json_file", "dfdc_files.json")):
with open(os.path.join("json_file", "dfdc_files.json")) as data_file:
dfdc_data = json.load(data_file)
if os.path.isfile(os.path.join(root_dir, "metadata.json")):
with open(os.path.join(root_dir, "metadata.json")) as data_file:
dfdc_meta = json.load(data_file)
model = load_genconvit(config, net, ed_weight, vae_weight, fp16)
count = 0
accuracy = 0
for dfdc in dfdc_data:
dfdc_file = os.path.join(root_dir, dfdc)
try:
if is_video(dfdc_file):
result, accuracy, count, _ = predict(
dfdc_file,
model,
fp16,
result,
num_frames,
net,
"dfdc",
count,
accuracy,
dfdc_meta[dfdc]["label"],
)
else:
print(f"Invalid video file: {dfdc_file}. Please provide a valid video file.")
except Exception as e:
print(f"An error occurred: {str(e)}")
return result
def celeb(ed_weight, vae_weight, root_dir="Celeb-DF-v2", dataset=None, num_frames=15, net=None, fp16=False):
with open(os.path.join("json_file", "celeb_test.json"), "r") as f:
cfl = json.load(f)
result = set_result()
ky = ["Celeb-real", "Celeb-synthesis"]
count = 0
accuracy = 0
model = load_genconvit(config, net, ed_weight, vae_weight, fp16)
for ck in cfl:
ck_ = ck.split("/")
klass = ck_[0]
filename = ck_[1]
correct_label = "FAKE" if klass == "Celeb-synthesis" else "REAL"
vid = os.path.join(root_dir, ck)
try:
if is_video(vid):
result, accuracy, count, _ = predict(
vid,
model,
fp16,
result,
num_frames,
net,
klass,
count,
accuracy,
correct_label,
)
else:
print(f"Invalid video file: {vid}. Please provide a valid video file.")
except Exception as e:
print(f"An error occurred x: {str(e)}")
return result
def predict(
vid,
model,
fp16,
result,
num_frames,
net,
klass,
count=0,
accuracy=-1,
correct_label="unknown",
compression=None,
vid_folder=None
):
count += 1
print(f"\n\n{str(count)} Loading... {vid}")
start_time = perf_counter()
# locate the extracted frames of the video if provided.
if vid_folder:
df = df_face_from_folder(vid, num_frames)
else:
df = df_face(vid, num_frames) # extract face from the frames
if len(df) == 0:
print(f"Warning: No faces detected in {vid}. Skipping prediction.")
# Return a value indicating that the prediction was skipped
return result, accuracy, count, [None, None]
if fp16:
df.half()
y, y_val = pred_vid(df, model)
result = store_result(
result, os.path.basename(vid), y, y_val, klass, correct_label, compression
)
if accuracy > -1:
if correct_label == real_or_fake(y):
accuracy += 1
print(
f"\nPrediction: {y_val} {real_or_fake(y)} \t\t {accuracy}/{count} {accuracy/count}"
)
end_time = perf_counter()
print("\n\n only one video--- %s seconds ---" % (end_time - start_time))
return result, accuracy, count, [y, y_val]
def gen_parser():
parser = argparse.ArgumentParser("GenConViT prediction")
parser.add_argument("--p", type=str, help="video or image path")
parser.add_argument(
"--f", type=int, help="number of frames to process for prediction"
)
parser.add_argument(
"--d", type=str, help="dataset type, dfdc, faceforensics, timit, celeb"
)
parser.add_argument(
"--s", help="model size type: tiny, large.",
)
parser.add_argument(
"--e", nargs='?', const='genconvit_ed_inference', default=None, help="weight for ed.",
)
parser.add_argument(
"--v", '--value', nargs='?', const='genconvit_vae_inference', default=None, help="weight for vae.",
)
parser.add_argument("--fp16", type=str, help="half precision support")
args = parser.parse_args()
path = args.p
num_frames = args.f if args.f else 15
dataset = args.d if args.d else "other"
fp16 = True if args.fp16 else False
net = 'genconvit'
ed_weight = None
vae_weight = None
if args.e and args.v:
ed_weight = 'genconvit_ed_inference'
vae_weight = 'genconvit_vae_inference'
elif args.e:
net = 'ed'
ed_weight = 'genconvit_ed_inference'
elif args.v:
net = 'vae'
vae_weight = 'genconvit_vae_inference'
print(f'\nUsing {net}\n')
if args.s:
if args.s in ['tiny', 'large']:
config["model"]["backbone"] = f"convnext_{args.s}"
config["model"]["embedder"] = f"swin_{args.s}_patch4_window7_224"
config["model"]["type"] = args.s
return path, dataset, num_frames, net, fp16, ed_weight, vae_weight
def main():
start_time = perf_counter()
path, dataset, num_frames, net, fp16, ed_weight, vae_weight = gen_parser()
result = (
globals()[dataset](ed_weight, vae_weight, path, dataset, num_frames, net, fp16)
if dataset in ["dfdc", "faceforensics", "timit", "celeb"]
else vids(ed_weight, vae_weight, path, dataset, num_frames, net, fp16)
)
curr_time = datetime.now().strftime("%B_%d_%Y_%H_%M_%S")
file_path = os.path.join("result", f"prediction_{dataset}_{net}_{curr_time}.json")
with open(file_path, "w") as f:
json.dump(result, f)
end_time = perf_counter()
print("\n\n--- %s seconds ---" % (end_time - start_time))
if __name__ == "__main__":
main()
|