Spaces:
Sleeping
Sleeping
File size: 49,641 Bytes
36ca064 5163e36 36ca064 28d9e73 36ca064 5163e36 36ca064 5163e36 36ca064 5163e36 36ca064 5163e36 36ca064 5163e36 36ca064 5163e36 36ca064 5163e36 c47d277 |
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 |
# # #!/usr/bin/env python3
# # import os
# # import csv
# # import time
# # import base64
# # from pathlib import Path
# # from tqdm import tqdm
# # import logging
# # from PIL import Image
# # import io
# # from datetime import datetime
# # from openai import OpenAI
# # import numpy as np
# # # === RetinaFace Configuration ===
# # try:
# # from retinaface import RetinaFace
# # RETINAFACE_AVAILABLE = True
# # except ImportError:
# # RETINAFACE_AVAILABLE = False
# # print("β ERROR: RetinaFace library not found. Please run 'pip install retina-face'. Running without face cropping.")
# # # === LOGGING CONFIG ===
# # os.makedirs("logs", exist_ok=True)
# # logging.basicConfig(
# # filename=f"logs/run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log",
# # level=logging.INFO,
# # format="%(asctime)s - %(levelname)s - %(message)s",
# # )
# # logger = logging.getLogger(__name__)
# # class DeepfakeDetector:
# # """Deepfake Detection System (Qwen / GPT / Gemini / Llama / Cohere) with RetinaFace + adaptive delay"""
# # def __init__(self, api_key, model_name="qwen", debug_mode=False, start_from=0, use_face_detector=True):
# # self.api_key = api_key
# # self.model_name = model_name.lower()
# # self.debug_mode = debug_mode
# # self.start_from = start_from
# # self.dataset_folder = "dataset"
# # self.results_folder = "result"
# # self.csv_filename = f"result_{self.model_name}_{start_from}.csv"
# # # === OpenRouter API client ===
# # self.client = OpenAI(
# # base_url="https://openrouter.ai/api/v1",
# # api_key=self.api_key,
# # )
# # self.extra_headers = {
# # "HTTP-Referer": "https://github.com/retinaface-comparison",
# # "X-Title": "Deepfake Detection Adaptive"
# # }
# # # === Model map (5 LLMs) ===
# # self.model_map = {
# # "qwen": "qwen/qwen3-vl-8b-instruct",
# # "gpt": "openai/chatgpt-4o-latest",
# # "gemini": "google/gemini-2.5-flash",
# # "llama": "meta-llama/llama-3.2-90b-vision-instruct",
# # "cohere": "cohere/command-r-plus-08-2024",
# # }
# # if self.model_name not in self.model_map:
# # raise ValueError("β Invalid model name. Choose from: qwen, gpt, gemini, llama, cohere")
# # logger.info(f"Model selected: {self.model_name.upper()} ({self.model_map[self.model_name]})")
# # os.makedirs(self.results_folder, exist_ok=True)
# # self.use_face_detector = use_face_detector and RETINAFACE_AVAILABLE
# # self.target_size = 512
# # # Adaptive delay system
# # self.delay = 0.5
# # self.fail_count = 0
# # self.success_count = 0
# # print(f"\nModel: {self.model_name.upper()} | RetinaFace Cropping: {'ON' if self.use_face_detector else 'OFF'}")
# # # === Image handling (RetinaFace) ===
# # def preprocess_image_with_retinaface(self, image_path):
# # if not self.use_face_detector or not RETINAFACE_AVAILABLE:
# # return self.encode_image_simple(image_path)
# # try:
# # faces = RetinaFace.detect_faces(image_path)
# # if not faces:
# # logger.warning(f"No face detected in {image_path}")
# # return self.encode_image_simple(image_path)
# # # Ambil wajah utama
# # first_face = list(faces.values())[0]
# # facial_area = first_face.get("facial_area", None)
# # if not facial_area or len(facial_area) != 4:
# # return self.encode_image_simple(image_path)
# # x1, y1, x2, y2 = facial_area
# # img = Image.open(image_path).convert("RGB")
# # cropped_img = img.crop((x1, y1, x2, y2))
# # cropped_img = cropped_img.resize((self.target_size, self.target_size))
# # buf = io.BytesIO()
# # cropped_img.save(buf, format="JPEG", quality=90, optimize=True)
# # encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
# # return f"data:image/jpeg;base64,{encoded}"
# # except Exception as e:
# # logger.error(f"RetinaFace error on {image_path}: {e}")
# # return self.encode_image_simple(image_path)
# # def encode_image_simple(self, image_path):
# # try:
# # with open(image_path, "rb") as f:
# # encoded = base64.b64encode(f.read()).decode("utf-8")
# # return f"data:image/jpeg;base64,{encoded}"
# # except Exception as e:
# # logger.error(f"Encode error: {e}")
# # return None
# # def validate_image(self, image_path):
# # try:
# # if not os.path.exists(image_path):
# # return False
# # with Image.open(image_path) as img:
# # img.verify()
# # return True
# # except Exception:
# # return False
# # def normalize_output(self, content):
# # if not content:
# # return "UNKNOWN"
# # text = content.strip().upper()
# # if any(w in text for w in ["REAL", "GENUINE", "HUMAN"]):
# # return "REAL"
# # if any(w in text for w in ["FAKE", "DEEPFAKE", "AI", "SYNTHETIC", "GENERATED"]):
# # return "FAKE"
# # if "NOT FAKE" in text or "LOOKS REAL" in text:
# # return "REAL"
# # if "PROBABLY FAKE" in text or "MAYBE FAKE" in text:
# # return "FAKE"
# # return "UNKNOWN"
# # def reverify_qwen(self, img_b64, prev_result):
# # prompt = (
# # "Re-analyze this face image for deepfake signs. "
# # "Focus on lighting, symmetry, and unnatural skin artifacts. "
# # "Respond with one word only: REAL or FAKE."
# # )
# # print(f"π Re-verifying Qwen result (was {prev_result})...")
# # try:
# # resp = self.client.chat.completions.create(
# # extra_headers=self.extra_headers,
# # model=self.model_map["qwen"],
# # messages=[{
# # "role": "user",
# # "content": [
# # {"type": "image_url", "image_url": {"url": img_b64}},
# # {"type": "text", "text": prompt}
# # ]
# # }],
# # max_tokens=50,
# # temperature=0.1,
# # )
# # content = resp.choices[0].message.content.strip().upper()
# # if "FAKE" in content:
# # print("β
Changed to FAKE after second check")
# # return "FAKE"
# # elif "REAL" in content:
# # print("β
Confirmed REAL after second check")
# # return "REAL"
# # else:
# # print("β οΈ Still ambiguous after recheck")
# # return prev_result
# # except Exception as e:
# # print(f"β οΈ Qwen re-verification failed: {e}")
# # return prev_result
# # # === Deteksi utama ===
# # def detect_deepfake_llm(self, image_path):
# # prompt = (
# # "You are a forensic image analyst. Analyze this face image for any deepfake or AI manipulation. "
# # "Consider lighting, eyes, skin, and blending. Respond with only one word: REAL or FAKE."
# # )
# # if not self.validate_image(image_path):
# # return "ERROR", None, "invalid"
# # img_b64 = self.preprocess_image_with_retinaface(image_path)
# # if not img_b64:
# # return "ERROR", None, "invalid"
# # model_id = self.model_map[self.model_name]
# # method = "retinaface_crop" if self.use_face_detector else "original"
# # try:
# # resp = self.client.chat.completions.create(
# # extra_headers=self.extra_headers,
# # model=model_id,
# # messages=[{
# # "role": "user",
# # "content": [
# # {"type": "image_url", "image_url": {"url": img_b64}},
# # {"type": "text", "text": prompt}
# # ]
# # }],
# # max_tokens=50,
# # temperature=0.1,
# # )
# # content = resp.choices[0].message.content
# # result = self.normalize_output(content)
# # if self.model_name == "qwen" and result == "REAL":
# # result = self.reverify_qwen(img_b64, result)
# # return result, content, method
# # except Exception as e:
# # logger.error(f"Detection failed: {e}")
# # return "ERROR", None, method
# # # === Dataset & Resume ===
# # def get_images(self):
# # dataset_path = Path(self.dataset_folder)
# # real_path = dataset_path / "face_real"
# # fake_path = dataset_path / "face_fake"
# # if not real_path.exists() or not fake_path.exists():
# # print("β Dataset folders missing.")
# # return []
# # real_images = sorted(list(real_path.glob("*.jpg")))[:500]
# # fake_images = sorted(list(fake_path.glob("*.jpg")))[:500]
# # return [(str(p), "REAL") for p in real_images] + [(str(p), "FAKE") for p in fake_images]
# # def load_existing_results(self):
# # csv_path = os.path.join(self.results_folder, self.csv_filename)
# # if not os.path.exists(csv_path):
# # return []
# # results = []
# # with open(csv_path, "r", encoding="utf-8") as f:
# # reader = csv.reader(f)
# # next(reader)
# # for row in reader:
# # if len(row) >= 5:
# # results.append((row[0], row[1], row[2], row[3], row[4]))
# # logger.info(f"Loaded {len(results)} existing results")
# # return results
# # def save_results_to_csv(self, results):
# # csv_path = os.path.join(self.results_folder, self.csv_filename)
# # with open(csv_path, "w", newline="", encoding="utf-8") as f:
# # writer = csv.writer(f)
# # writer.writerow(["filename", "ground_truth", "llm_result", "model_name", "method"])
# # writer.writerows(results)
# # logger.info(f"Saved {len(results)} results to {csv_path}")
# # # === Adaptive delay logic ===
# # def adjust_delay(self):
# # if self.fail_count > 5:
# # self.delay = min(self.delay + 0.2, 2.0)
# # logger.warning(f"Increasing delay to {self.delay:.1f}s due to failures.")
# # self.fail_count = 0
# # elif self.success_count > 10:
# # self.delay = max(self.delay - 0.1, 0.3)
# # logger.info(f"Reducing delay to {self.delay:.1f}s (stable).")
# # self.success_count = 0
# # def run_detection(self, resume=True):
# # all_images = self.get_images()
# # if not all_images:
# # return
# # results = self.load_existing_results() if resume else []
# # processed = {r[0] for r in results}
# # remaining = [(p, gt) for p, gt in all_images if os.path.basename(p) not in processed]
# # print(f"\n=== STARTING {self.model_name.upper()} DETECTION ===")
# # print(f"Total: {len(all_images)} | Already done: {len(processed)} | Remaining: {len(remaining)}")
# # with tqdm(total=len(remaining), desc=f"{self.model_name.upper()}") as pbar:
# # for img_path, truth in remaining:
# # try:
# # result, response, method = self.detect_deepfake_llm(img_path)
# # results.append((os.path.basename(img_path), truth, result, self.model_name, method))
# # self.success_count += 1
# # except Exception as e:
# # logger.error(f"Fatal error: {e}")
# # results.append((os.path.basename(img_path), truth, "ERROR", self.model_name, "error"))
# # self.fail_count += 1
# # pbar.set_description(f"{os.path.basename(img_path)} -> {result}")
# # pbar.update(1)
# # self.save_results_to_csv(results)
# # self.adjust_delay()
# # time.sleep(self.delay)
# # print(f"\nβ
Detection completed for {self.model_name.upper()}")
# # print(f"Results saved to: {os.path.join(self.results_folder, self.csv_filename)}")
# #!/usr/bin/env python3
# #!/usr/bin/env python3
# import os
# import csv
# import time
# import base64
# from pathlib import Path
# from tqdm import tqdm
# import logging
# from PIL import Image
# import io
# from datetime import datetime
# from openai import OpenAI
# import numpy as np
# import math # Diperlukan untuk perhitungan akurasi
# # RetinaFace Configuration
# try:
# #retinaface
# from retinaface import RetinaFace
# RETINAFACE_AVAILABLE = True
# except ImportError:
# RETINAFACE_AVAILABLE = False
# print("β ERROR: RetinaFace library not found. Running without face cropping.")
# # === LOGGING CONFIG ===
# os.makedirs("logs", exist_ok=True)
# logging.basicConfig(
# filename=f"logs/run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log",
# level=logging.INFO,
# format="%(asctime)s - %(levelname)s - %(message)s",
# )
# logger = logging.getLogger(__name__)
# class DeepfakeDetector:
# """Deepfake Detection System (Qwen / GPT / Gemini / Llama / Cohere) with RetinaFace + adaptive delay"""
# def __init__(self, api_key, model_name="qwen", debug_mode=False, start_from=0, use_face_detector=True):
# self.api_key = api_key
# self.model_name = model_name.lower()
# self.debug_mode = debug_mode
# self.start_from = start_from
# self.dataset_folder = "dataset"
# self.results_folder = "result"
# self.csv_filename = f"result_{self.model_name}_{start_from}.csv"
# # OpenRouter API client
# self.client = OpenAI(
# base_url="https://openrouter.ai/api/v1",
# api_key=self.api_key,
# )
# self.extra_headers = {
# "HTTP-Referer": "https://github.com/retinaface-comparison",
# "X-Title": "Deepfake Detection Adaptive"
# }
# # Model map (5 LLMs via OpenRouter)
# self.model_map = {
# "qwen": "qwen/qwen3-vl-8b-instruct",
# "gpt": "openai/chatgpt-4o-latest",
# "gemini": "google/gemini-2.5-flash",
# "llama": "meta-llama/llama-3.2-90b-vision-instruct",
# "cohere": "cohere/command-r-plus-08-2024",
# }
# if self.model_name not in self.model_map:
# raise ValueError("β Invalid model name. Choose from: qwen, gpt, gemini, llama, cohere")
# logger.info(f"Model selected: {self.model_name.upper()} ({self.model_map[self.model_name]})")
# os.makedirs(self.results_folder, exist_ok=True)
# self.use_face_detector = use_face_detector and RETINAFACE_AVAILABLE
# self.target_size = 512
# # waktu delay
# self.delay = 0.3
# self.fail_count = 0
# self.success_count = 0
# print(f"\nModel: {self.model_name.upper()} | RetinaFace Cropping: {'ON' if self.use_face_detector else 'OFF'}")
# # Image handling (RetinaFace)
# def preprocess_image_with_retinaface(self, image_path):
# if not self.use_face_detector or not RETINAFACE_AVAILABLE:
# return self.encode_image_simple(image_path)
# try:
# # Perlu diubah ke string karena RetinaFace kadang tidak menerima objek Path
# faces = RetinaFace.detect_faces(str(image_path))
# if not faces:
# logger.warning(f"No face detected in {image_path}")
# return self.encode_image_simple(image_path)
# first_face = list(faces.values())[0]
# facial_area = first_face.get("facial_area", None)
# if not facial_area or len(facial_area) != 4:
# return self.encode_image_simple(image_path)
# x1, y1, x2, y2 = facial_area
# img = Image.open(image_path).convert("RGB")
# # Tambahkan margin (ekstraksi)
# margin_ratio = 0.2
# w, h = x2 - x1, y2 - y1
# margin_x = int(w * margin_ratio)
# margin_y = int(h * margin_ratio)
# x1 = max(0, x1 - margin_x)
# y1 = max(0, y1 - margin_y)
# x2 = min(img.width, x2 + margin_x)
# y2 = min(img.height, y2 + margin_y)
# cropped_img = img.crop((x1, y1, x2, y2))
# cropped_img = cropped_img.resize((self.target_size, self.target_size), Image.Resampling.LANCZOS)
# buf = io.BytesIO()
# cropped_img.save(buf, format="JPEG", quality=90, optimize=True)
# encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
# return f"data:image/jpeg;base64,{encoded}"
# except Exception as e:
# logger.error(f"RetinaFace error on {image_path}: {e}")
# return self.encode_image_simple(image_path)
# def encode_image_simple(self, image_path):
# try:
# with open(image_path, "rb") as f:
# encoded = base64.b64encode(f.read()).decode("utf-8")
# return f"data:image/jpeg;base64,{encoded}"
# except Exception as e:
# logger.error(f"Encode error: {e}")
# return None
# def validate_image(self, image_path):
# try:
# if not os.path.exists(image_path):
# return False
# with Image.open(image_path) as img:
# img.verify()
# return True
# except Exception:
# return False
# def normalize_output(self, content):
# """
# Normalizes verbose LLM output to a single word: REAL, FAKE, or UNKNOWN.
# """
# if not content:
# return "UNKNOWN"
# text = content.strip().upper()
# # Mencari kata kunci FAKE
# if any(w in text for w in ["FAKE", "DEEPFAKE", "AI GENERATED", "SYNTHETIC"]):
# return "FAKE"
# # Mencari kata kunci REAL
# if any(w in text for w in ["REAL", "GENUINE", "HUMAN", "NOT FAKE"]):
# return "REAL"
# # Upaya kedua: Coba ambil kata pertama/kata kunci di tengah respons
# words = text.split()
# if words:
# for word in words[:3]: # Cek 3 kata pertama
# if "REAL" in word: return "REAL"
# if "FAKE" in word: return "FAKE"
# logger.warning(f"Output ambiguous/unpredictable: {content}")
# return "UNKNOWN"
# def reverify_qwen(self, img_b64, prev_result):
# # Logika re-verifikasi
# prompt = (
# "Re-analyze this face image for deepfake signs. "
# "Focus on lighting, symmetry, and unnatural skin artifacts. "
# "Respond with one word only: REAL or FAKE."
# )
# print(f"π Re-verifying Qwen result (was {prev_result})...")
# try:
# resp = self.client.chat.completions.create(
# extra_headers=self.extra_headers,
# model=self.model_map["qwen"],
# messages=[{
# "role": "user",
# "content": [
# {"type": "image_url", "image_url": {"url": img_b64}},
# {"type": "text", "text": prompt}
# ]
# }],
# max_tokens=50,
# temperature=0.1,
# )
# content = resp.choices[0].message.content.strip().upper()
# if "FAKE" in content:
# print("Changed to FAKE after second check")
# return "FAKE"
# elif "REAL" in content:
# print("Confirmed REAL after second check")
# return "REAL"
# else:
# print("Still ambiguous after recheck")
# return prev_result
# except Exception as e:
# print(f"Qwen re-verification failed: {e}")
# return prev_result
# # Fungsi Fallback
# def retinaface_simple_fallback(self, image_path):
# """Applies a heuristic rule if LLM returns an error."""
# if not self.use_face_detector or not RETINAFACE_AVAILABLE:
# return 'UNKNOWN_FALLBACK'
# try:
# # Panggil deteksi wajah (menggunakan str(image_path))
# faces = RetinaFace.detect_faces(str(image_path))
# if not faces:
# return 'UNKNOWN_FALLBACK'
# best_score = max(f['score'] for f in faces.values())
# # Aturan Heuristik: Jika skor kepercayaan wajah sangat tinggi, REAL.
# if best_score > 0.995:
# return 'REAL'
# else:
# return 'UNKNOWN_FALLBACK'
# except Exception:
# return 'UNKNOWN_FALLBACK'
# # Deteksi utama
# def detect_deepfake_llm(self, image_path):
# prompt = (
# "You are a forensic image analyst. Analyze this face image for any deepfake or AI manipulation. "
# "Consider lighting, eyes, skin, and blending. Respond with only one word: REAL or FAKE."
# )
# if not self.validate_image(image_path):
# return "ERROR", None, "invalid"
# img_b64 = self.preprocess_image_with_retinaface(image_path)
# if not img_b64:
# return "ERROR", None, "invalid"
# model_id = self.model_map[self.model_name]
# method = "retinaface_crop" if self.use_face_detector else "original"
# try:
# resp = self.client.chat.completions.create(
# extra_headers=self.extra_headers,
# model=model_id,
# messages=[{
# "role": "user",
# "content": [
# {"type": "image_url", "image_url": {"url": img_b64}},
# {"type": "text", "text": prompt}
# ]
# }],
# max_tokens=50,
# temperature=0.1,
# )
# content = resp.choices[0].message.content
# result = self.normalize_output(content)
# if self.model_name == "qwen" and result == "REAL":
# result = self.reverify_qwen(img_b64, result)
# return result, content, method
# except Exception as e:
# logger.error(f"Detection failed: {e}")
# # Tambahkan logika Fallback RetinaFace
# fallback_result = self.retinaface_simple_fallback(image_path)
# logger.warning(f"LLM Failed. Applying Fallback Logic: {fallback_result}")
# if fallback_result == 'REAL':
# # Jika heuristik RetinaFace yakin gambar BERKUALITAS BAGUS, prediksi REAL
# return 'REAL', "RetinaFace Heuristic", "retinaface_crop_FALLBACK"
# else:
# return "FAKE", "RetinaFace Heuristic (Assumed FAKE)", "retinaface_crop"
# # === Dataset & Resume ===
# def get_images(self):
# dataset_path = Path(self.dataset_folder)
# real_path = dataset_path / "face_real"
# fake_path = dataset_path / "face_fake"
# if not real_path.exists() or not fake_path.exists():
# print("β Dataset folders missing.")
# return []
# # Batasi gambar menjadi 500 REAL dan 500 FAKE (total 1000)
# real_images = sorted(list(real_path.glob("*.jpg")))[:500]
# fake_images = sorted(list(fake_path.glob("*.jpg")))[:500]
# return [(str(p), "REAL") for p in real_images] + [(str(p), "FAKE") for p in fake_images]
# def load_existing_results(self):
# csv_path = os.path.join(self.results_folder, self.csv_filename)
# if not os.path.exists(csv_path):
# return []
# results = []
# with open(csv_path, "r", encoding="utf-8") as f:
# reader = csv.reader(f)
# next(reader)
# for row in reader:
# # baris memiliki 5 kolom
# if len(row) >= 5:
# results.append((row[0], row[1], row[2], row[3], row[4]))
# logger.info(f"Loaded {len(results)} existing results")
# return results
# def save_results_to_csv(self, results):
# csv_path = os.path.join(self.results_folder, self.csv_filename)
# with open(csv_path, "w", newline="", encoding="utf-8") as f:
# writer = csv.writer(f)
# writer.writerow(["filename", "ground_truth", "llm_result", "model_name", "method"])
# writer.writerows(results)
# logger.info(f"Saved {len(results)} results to {csv_path}")
# # logika delay
# def adjust_delay(self):
# # Logika adaptive delay
# if self.fail_count > 5:
# self.delay = min(self.delay + 0.2, 2.0)
# logger.warning(f"Increasing delay to {self.delay:.1f}s due to failures.")
# self.fail_count = 0
# elif self.success_count > 10:
# self.delay = max(self.delay - 0.1, 0.3)
# logger.info(f"Reducing delay to {self.delay:.1f}s (stable).")
# self.success_count = 0
# def run_detection(self, resume=True):
# all_images = self.get_images()
# if not all_images:
# return
# results = self.load_existing_results() if resume else []
# processed = {r[0] for r in results}
# remaining = [(p, gt) for p, gt in all_images if os.path.basename(p) not in processed]
# print(f"\n=== STARTING {self.model_name.upper()} DETECTION ===")
# print(f"Total: {len(all_images)} | Already done: {len(processed)} | Remaining: {len(remaining)}")
# with tqdm(total=len(remaining), desc=f"{self.model_name.upper()}") as pbar:
# for img_path, truth in remaining:
# try:
# result, response, method = self.detect_deepfake_llm(img_path)
# results.append((os.path.basename(img_path), truth, result, self.model_name, method))
# self.success_count += 1
# except Exception as e:
# logger.error(f"Fatal error: {e}")
# results.append((os.path.basename(img_path), truth, "ERROR", self.model_name, "error"))
# self.fail_count += 1
# pbar.set_description(f"{os.path.basename(img_path)} -> {result}")
# pbar.update(1)
# self.save_results_to_csv(results)
# self.adjust_delay()
# time.sleep(self.delay)
# print(f"\nβ
Deteksi selesai untuk {self.model_name.upper()}")
# print(f"Hasil simpan ke: {os.path.join(self.results_folder, self.csv_filename)}")
# #!/usr/bin/env python3
# import os
# import csv
# import time
# import base64
# from pathlib import Path
# from tqdm import tqdm
# import logging
# from PIL import Image
# import io
# from datetime import datetime
# from openai import OpenAI
# import numpy as np
# import math
# # === RetinaFace Configuration ===
# try:
# from retinaface import RetinaFace
# RETINAFACE_AVAILABLE = True
# except ImportError:
# RETINAFACE_AVAILABLE = False
# print("β ERROR: RetinaFace library not found. Please run 'pip install retina-face'. Running without face cropping.")
# # === LOGGING CONFIG ===
# os.makedirs("logs", exist_ok=True)
# logging.basicConfig(
# filename=f"logs/run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log",
# level=logging.INFO,
# format="%(asctime)s - %(levelname)s - %(message)s",
# )
# logger = logging.getLogger(__name__)
# class DeepfakeDetector:
# """Deepfake Detection System (Qwen / GPT / Gemini / Llama / Cohere) with RetinaFace + adaptive delay"""
# def __init__(self, api_key, model_name="qwen", debug_mode=False, start_from=0, use_face_detector=True):
# self.api_key = api_key
# self.model_name = model_name.lower()
# self.debug_mode = debug_mode
# self.start_from = start_from
# self.dataset_folder = "dataset"
# self.results_folder = "result"
# self.csv_filename = f"result_{self.model_name}_{start_from}.csv"
# # === OpenRouter API client (Menggunakan OpenRouter untuk semua model) ===
# self.client = OpenAI(
# base_url="https://openrouter.ai/api/v1",
# api_key=self.api_key,
# )
# self.extra_headers = {
# "HTTP-Referer": "https://github.com/retinaface-comparison",
# "X-Title": "Deepfake Detection Adaptive"
# }
# # === Model map (5 LLMs via OpenRouter) ===
# self.model_map = {
# "qwen": "qwen/qwen3-vl-8b-instruct",
# "gpt": "openai/chatgpt-4o-latest",
# "gemini": "google/gemini-2.5-flash",
# "llama": "meta-llama/llama-3.2-90b-vision-instruct",
# "cohere": "cohere/command-r-plus-08-2024",
# }
# if self.model_name not in self.model_map:
# raise ValueError("β Invalid model name. Choose from: qwen, gpt, gemini, llama, cohere")
# logger.info(f"Model selected: {self.model_name.upper()} ({self.model_map[self.model_name]})")
# os.makedirs(self.results_folder, exist_ok=True)
# self.use_face_detector = False and RETINAFACE_AVAILABLE
# self.target_size = 512
# # waktu delay
# self.delay = 0.3
# self.fail_count = 0
# self.success_count = 0
# print(f"\nModel: {self.model_name.upper()} | RetinaFace Cropping: {'ON' if self.use_face_detector else 'OFF'}")
# # === Image handling (RetinaFace) ===
# def preprocess_image_with_retinaface(self, image_path):
# if not self.use_face_detector or not RETINAFACE_AVAILABLE:
# return self.encode_image_simple(image_path)
# try:
# # Perlu diubah ke string karena RetinaFace kadang tidak menerima objek Path
# faces = RetinaFace.detect_faces(str(image_path))
# if not faces:
# logger.warning(f"No face detected in {image_path}")
# return self.encode_image_simple(image_path)
# first_face = list(faces.values())[0]
# facial_area = first_face.get("facial_area", None)
# if not facial_area or len(facial_area) != 4:
# return self.encode_image_simple(image_path)
# x1, y1, x2, y2 = facial_area
# img = Image.open(image_path).convert("RGB")
# # Tambahkan margin (ekstraksi)
# margin_ratio = 0.2
# w, h = x2 - x1, y2 - y1
# margin_x = int(w * margin_ratio)
# margin_y = int(h * margin_ratio)
# x1 = max(0, x1 - margin_x)
# y1 = max(0, y1 - margin_y)
# x2 = min(img.width, x2 + margin_x)
# y2 = min(img.height, y2 + margin_y)
# cropped_img = img.crop((x1, y1, x2, y2))
# cropped_img = cropped_img.resize((self.target_size, self.target_size), Image.Resampling.LANCZOS)
# buf = io.BytesIO()
# cropped_img.save(buf, format="JPEG", quality=90, optimize=True)
# encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
# return f"data:image/jpeg;base64,{encoded}"
# except Exception as e:
# logger.error(f"RetinaFace error on {image_path}: {e}")
# return self.encode_image_simple(image_path)
# def encode_image_simple(self, image_path):
# try:
# with open(image_path, "rb") as f:
# encoded = base64.b64encode(f.read()).decode("utf-8")
# return f"data:image/jpeg;base64,{encoded}"
# except Exception as e:
# logger.error(f"Encode error: {e}")
# return None
# def validate_image(self, image_path):
# try:
# if not os.path.exists(image_path):
# return False
# with Image.open(image_path) as img:
# img.verify()
# return True
# except Exception:
# return False
# def normalize_output(self, content):
# """
# Normalizes verbose LLM output to a single word: REAL, FAKE, or UNKNOWN.
# """
# if not content:
# return "UNKNOWN"
# text = content.strip().upper()
# # Mencari kata kunci FAKE (atau sinonim)
# if any(w in text for w in ["FAKE", "DEEPFAKE", "AI GENERATED", "SYNTHETIC"]):
# return "FAKE"
# # Mencari kata kunci REAL (atau sinonim)
# if any(w in text for w in ["REAL", "GENUINE", "HUMAN", "NOT FAKE"]):
# return "REAL"
# # Upaya kedua: Coba ambil kata pertama/kata kunci di tengah respons
# words = text.split()
# if words:
# for word in words[:3]: # Cek 3 kata pertama
# if "REAL" in word: return "REAL"
# if "FAKE" in word: return "FAKE"
# logger.warning(f"Output ambiguous/unpredictable: {content}")
# return "UNKNOWN"
# def reverify_qwen(self, img_b64, prev_result):
# # Logika re-verifikasi
# prompt = (
# "Re-analyze this face image for deepfake signs. "
# "Focus on lighting, symmetry, and unnatural skin artifacts. "
# "Respond with one word only: REAL or FAKE."
# )
# print(f"π Re-verifying Qwen result (was {prev_result})...")
# try:
# resp = self.client.chat.completions.create(
# extra_headers=self.extra_headers,
# model=self.model_map["qwen"],
# messages=[{
# "role": "user",
# "content": [
# {"type": "image_url", "image_url": {"url": img_b64}},
# {"type": "text", "text": prompt}
# ]
# }],
# max_tokens=50,
# temperature=0.1,
# )
# content = resp.choices[0].message.content.strip().upper()
# if "FAKE" in content:
# print("Changed to FAKE after second check")
# return "FAKE"
# elif "REAL" in content:
# print("Confirmed REAL after second check")
# return "REAL"
# else:
# print("Still ambiguous after recheck")
# return prev_result
# except Exception as e:
# print(f"Qwen re-verification failed: {e}")
# return prev_result
# # Fungsi Fallback Sederhana RetinaFace (Heuristik) DIHAPUS
# # === Deteksi utama ===
# def detect_deepfake_llm(self, image_path):
# prompt = (
# "You are a forensic image analyst. Analyze this face image for any deepfake or AI manipulation. "
# "Consider lighting, eyes, skin, and blending. Respond with only one word: REAL or FAKE."
# )
# if not self.validate_image(image_path):
# return "ERROR", None, "invalid"
# img_b64 = self.preprocess_image_with_retinaface(image_path)
# if not img_b64:
# return "ERROR", None, "invalid"
# model_id = self.model_map[self.model_name]
# method = "retinaface_crop" if self.use_face_detector else "original"
# try:
# resp = self.client.chat.completions.create(
# extra_headers=self.extra_headers,
# model=model_id,
# messages=[{
# "role": "user",
# "content": [
# {"type": "image_url", "image_url": {"url": img_b64}},
# {"type": "text", "text": prompt}
# ]
# }],
# max_tokens=50,
# temperature=0.1,
# )
# content = resp.choices[0].message.content
# result = self.normalize_output(content)
# if self.model_name == "qwen" and result == "REAL":
# result = self.reverify_qwen(img_b64, result)
# return result, content, method
# except Exception as e:
# logger.error(f"Detection failed: {e}")
# # --- LOGIKA KETIKA LLM GAGAL (TIDAK ADA TEBAKAN) ---
# # Jika LLM gagal, catat sebagai ERROR.
# return "ERROR", None, "API_FAILURE" # Mengganti 'error' dengan 'API_FAILURE' untuk kejelasan
# # === Dataset & Resume ===
# def get_images(self):
# dataset_path = Path(self.dataset_folder)
# real_path = dataset_path / "face_real"
# fake_path = dataset_path / "face_fake"
# if not real_path.exists() or not fake_path.exists():
# print("β Dataset folders missing.")
# return []
# # Batasi gambar menjadi 500 REAL dan 500 FAKE (total 1000)
# real_images = sorted(list(real_path.glob("*.jpg")))[:500]
# fake_images = sorted(list(fake_path.glob("*.jpg")))[:500]
# return [(str(p), "REAL") for p in real_images] + [(str(p), "FAKE") for p in fake_images]
# def load_existing_results(self):
# csv_path = os.path.join(self.results_folder, self.csv_filename)
# if not os.path.exists(csv_path):
# return []
# results = []
# with open(csv_path, "r", encoding="utf-8") as f:
# reader = csv.reader(f)
# next(reader)
# for row in reader:
# # Pastikan baris memiliki 5 kolom
# if len(row) >= 5:
# results.append((row[0], row[1], row[2], row[3], row[4]))
# logger.info(f"Loaded {len(results)} existing results")
# return results
# def save_results_to_csv(self, results):
# csv_path = os.path.join(self.results_folder, self.csv_filename)
# with open(csv_path, "w", newline="", encoding="utf-8") as f:
# writer = csv.writer(f)
# writer.writerow(["filename", "ground_truth", "llm_result", "model_name", "method"])
# writer.writerows(results)
# logger.info(f"Saved {len(results)} results to {csv_path}")
# # === Adaptive delay logic ===
# def adjust_delay(self):
# # Logika adaptive delay
# if self.fail_count > 5:
# self.delay = min(self.delay + 0.2, 2.0)
# logger.warning(f"Increasing delay to {self.delay:.1f}s due to failures.")
# self.fail_count = 0
# elif self.success_count > 10:
# self.delay = max(self.delay - 0.1, 0.3)
# logger.info(f"Reducing delay to {self.delay:.1f}s (stable).")
# self.success_count = 0
# def run_detection(self, resume=True):
# all_images = self.get_images()
# if not all_images:
# return
# results = self.load_existing_results() if resume else []
# processed = {r[0] for r in results}
# remaining = [(p, gt) for p, gt in all_images if os.path.basename(p) not in processed]
# print(f"\n=== STARTING {self.model_name.upper()} DETECTION ===")
# print(f"Total: {len(all_images)} | Already done: {len(processed)} | Remaining: {len(remaining)}")
# with tqdm(total=len(remaining), desc=f"{self.model_name.upper()}") as pbar:
# for img_path, truth in remaining:
# try:
# result, response, method = self.detect_deepfake_llm(img_path)
# results.append((os.path.basename(img_path), truth, result, self.model_name, method))
# self.success_count += 1
# except Exception as e:
# logger.error(f"Fatal error: {e}")
# results.append((os.path.basename(img_path), truth, "ERROR", self.model_name, "error"))
# self.fail_count += 1
# pbar.set_description(f"{os.path.basename(img_path)} -> {result}")
# pbar.update(1)
# self.save_results_to_csv(results)
# self.adjust_delay()
# time.sleep(self.delay)
# print(f"\nβ
Deteksi selesai untuk {self.model_name.upper()}")
# print(f"Hasil simpan ke: {os.path.join(self.results_folder, self.csv_filename)}")
import os
import time
import base64
from pathlib import Path
import logging
from PIL import Image
import io
from datetime import datetime
from openai import OpenAI
import numpy as np
# === RetinaFace Configuration ===
try:
from retinaface import RetinaFace
RETINAFACE_AVAILABLE = True
except ImportError:
RETINAFACE_AVAILABLE = False
# === LOGGING CONFIG ===
os.makedirs("logs", exist_ok=True)
logging.basicConfig(
filename=f"logs/run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
class DeepfakeDetector:
"""Deepfake Detection System (Qwen / GPT / Gemini / Llama / Cohere) for Single Image Inference"""
def __init__(self, api_key, model_name="qwen", use_face_detector=True):
self.api_key = api_key
self.model_name = model_name.lower()
# === OpenRouter API client ===
self.client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=self.api_key,
)
self.extra_headers = {
# Ganti Referer agar sesuai dengan Hugging Face
"HTTP-Referer": "https://huggingface.co/spaces/[your-username]/[your-space-name]",
"X-Title": f"Deepfake Detection Gradio ({self.model_name.upper()})"
}
# === Model map (5 LLMs via OpenRouter) ===
self.model_map = {
"qwen": "qwen/qwen3-vl-8b-instruct",
"gpt": "openai/chatgpt-4o-latest",
"gemini": "google/gemini-2.5-flash",
"llama": "meta-llama/llama-3.2-90b-vision-instruct",
# "cohere": "cohere/command-r-plus-08-2024",
}
if self.model_name not in self.model_map:
raise ValueError("β Invalid model name. Choose from: qwen, gpt, gemini, llama, cohere")
logger.info(f"Model selected: {self.model_name.upper()} ({self.model_map[self.model_name]})")
# diinisialisasi berdasarkan input
self.use_face_detector = use_face_detector and RETINAFACE_AVAILABLE
self.target_size = 512
# === Image handling (RetinaFace) ===
# FUNGSI INI TETAP TIDAK BERUBAH
def preprocess_image_with_retinaface(self, image_path):
if not self.use_face_detector or not RETINAFACE_AVAILABLE:
return self.encode_image_simple(image_path)
try:
faces = RetinaFace.detect_faces(str(image_path))
if not faces:
logger.warning(f"No face detected in {image_path}")
return self.encode_image_simple(image_path)
first_face = list(faces.values())[0]
facial_area = first_face.get("facial_area", None)
if not facial_area or len(facial_area) != 4:
return self.encode_image_simple(image_path)
x1, y1, x2, y2 = facial_area
img = Image.open(image_path).convert("RGB")
# Tambahkan margin (ekstraksi)
margin_ratio = 0.2
w, h = x2 - x1, y2 - y1
margin_x = int(w * margin_ratio)
margin_y = int(h * margin_ratio)
x1 = max(0, x1 - margin_x)
y1 = max(0, y1 - margin_y)
x2 = min(img.width, x2 + margin_x)
y2 = min(img.height, y2 + margin_y)
cropped_img = img.crop((x1, y1, x2, y2))
cropped_img = cropped_img.resize((self.target_size, self.target_size), Image.Resampling.LANCZOS)
buf = io.BytesIO()
cropped_img.save(buf, format="JPEG", quality=90, optimize=True)
encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
return f"data:image/jpeg;base64,{encoded}"
except Exception as e:
logger.error(f"RetinaFace error on {image_path}: {e}")
return self.encode_image_simple(image_path)
# FUNGSI encode
def encode_image_simple(self, image_path):
try:
with open(image_path, "rb") as f:
encoded = base64.b64encode(f.read()).decode("utf-8")
return f"data:image/jpeg;base64,{encoded}"
except Exception as e:
logger.error(f"Encode error: {e}")
return None
# FUNGSI validasi
def validate_image(self, image_path):
try:
if not os.path.exists(image_path):
return False
with Image.open(image_path) as img:
img.verify()
return True
except Exception:
return False
# FUNGSI normalize
def normalize_output(self, content):
"""
Normalizes verbose LLM output to a single word: REAL, FAKE, or UNKNOWN.
"""
if not content:
return "UNKNOWN"
text = content.strip().upper()
if any(w in text for w in ["FAKE", "DEEPFAKE", "AI GENERATED", "SYNTHETIC"]):
return "FAKE"
if any(w in text for w in ["REAL", "GENUINE", "HUMAN", "NOT FAKE"]):
return "REAL"
words = text.split()
if words:
for word in words[:3]:
if "REAL" in word: return "REAL"
if "FAKE" in word: return "FAKE"
logger.warning(f"Output ambiguous/unpredictable: {content}")
return "UNKNOWN"
# FUNGSI analisis qwen
def reverify_qwen(self, img_b64, prev_result):
prompt = (
"Re-analyze this face image for deepfake signs. "
"Focus on lighting, symmetry, and unnatural skin artifacts. "
"Respond with one word only: REAL or FAKE."
)
try:
resp = self.client.chat.completions.create(
extra_headers=self.extra_headers,
model=self.model_map["qwen"],
messages=[{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": img_b64}},
{"type": "text", "text": prompt}
]
}],
max_tokens=50,
temperature=0.1,
)
content = resp.choices[0].message.content.strip().upper()
if "FAKE" in content:
# print("Changed to FAKE after second check")
return "FAKE"
elif "REAL" in content:
# print("Confirmed REAL after second check")
return "REAL"
else:
# print("Still ambiguous after recheck")
return prev_result
except Exception as e:
# print(f"Qwen re-verification failed: {e}")
return prev_result
# === Deteksi utama ===
def detect_deepfake_llm(self, image_path):
prompt = (
"You are a forensic image analyst. Analyze this face image for any deepfake or AI manipulation. "
"Consider lighting, eyes, skin, and blending. Respond with only one word: REAL or FAKE."
)
if not self.validate_image(image_path):
return "ERROR", None, "invalid"
img_b64 = self.preprocess_image_with_retinaface(image_path)
if not img_b64:
return "ERROR", None, "invalid"
model_id = self.model_map[self.model_name]
method = "retinaface_crop" if self.use_face_detector else "original"
try:
resp = self.client.chat.completions.create(
extra_headers=self.extra_headers,
model=model_id,
messages=[{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": img_b64}},
{"type": "text", "text": prompt}
]
}],
max_tokens=50,
temperature=0.1,
)
content = resp.choices[0].message.content
result = self.normalize_output(content)
if self.model_name == "qwen" and result == "REAL":
result = self.reverify_qwen(img_b64, result)
return result, content, method
except Exception as e:
logger.error(f"Detection failed: {e}")
return "ERROR", None, "API_FAILURE"
pass # Pass diletakkan di sini hanya sebagai penanda bahwa sisanya telah dihapus. |