-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_diff.py
More file actions
3968 lines (3349 loc) · 142 KB
/
Copy pathcheck_diff.py
File metadata and controls
3968 lines (3349 loc) · 142 KB
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
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import threading
import subprocess
import json
import os
import tempfile
import hashlib
from pathlib import Path
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
from datetime import datetime
import numpy as np
from PIL import Image
import imagehash
import librosa
import cv2
import base64
from io import BytesIO
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend
import matplotlib.pyplot as plt
from scipy import signal
from scipy.spatial.distance import cosine as cosine_distance
from sklearn.metrics.pairwise import cosine_similarity as sklearn_cosine_similarity
# Optional: CLIP for deep content embedding
try:
import torch
import clip as clip_module
CLIP_AVAILABLE = True
CLIP_MODEL = None
CLIP_PREPROCESS = None
CLIP_DEVICE = None
except ImportError:
CLIP_AVAILABLE = False
CLIP_MODEL = None
CLIP_PREPROCESS = None
CLIP_DEVICE = None
# Optional: YOLO for logo/watermark detection
try:
from ultralytics import YOLO
YOLO_AVAILABLE = True
YOLO_MODEL = None
except ImportError:
YOLO_AVAILABLE = False
YOLO_MODEL = None
# Optional: Chromaprint for audio fingerprinting
try:
import acoustid
import chromaprint
CHROMAPRINT_AVAILABLE = True
except ImportError:
CHROMAPRINT_AVAILABLE = False
# Optional: Tesseract for OCR text detection
try:
import pytesseract
from pytesseract import TesseractNotFoundError
TESSERACT_AVAILABLE = True
# Auto-detect Tesseract path on Windows
if os.name == 'nt': # Windows
possible_paths = [
r'libs\Tesseract-OCR\tesseract.exe',
r'libs\Tesseract-OCR\tTesseract-OCR\tesseract.exe',
r'C:\Program Files\Tesseract-OCR\tesseract.exe',
r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe',
r'C:\Tesseract-OCR\tesseract.exe',
os.path.expanduser(r'~\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'),
os.path.expanduser(r'~\AppData\Local\Tesseract-OCR\tesseract.exe'),
]
# Try to find Tesseract
tesseract_found = False
for path in possible_paths:
if os.path.exists(path):
pytesseract.pytesseract.tesseract_cmd = path
tesseract_found = True
break
if not tesseract_found:
print("Warning: Tesseract not found in common locations. OCR features will be disabled.")
print("See guilde at /libs/README.md for more information.")
TESSERACT_AVAILABLE = False
except ImportError:
TESSERACT_AVAILABLE = False
TesseractNotFoundError = Exception # Fallback
except Exception as e:
print(f"Tesseract configuration error: {e}")
TESSERACT_AVAILABLE = False
TesseractNotFoundError = Exception # Fallback
# Optional: Report generation libraries
try:
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, Table, TableStyle, PageBreak
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
REPORTLAB_AVAILABLE = True
except ImportError:
REPORTLAB_AVAILABLE = False
try:
from jinja2 import Template
JINJA2_AVAILABLE = True
except ImportError:
JINJA2_AVAILABLE = False
def _to_float(x: Any) -> Optional[float]:
try:
return float(x)
except Exception:
return None
def _to_int(x: Any) -> Optional[int]:
try:
return int(x)
except Exception:
return None
def validate_number(x: Any, default: Optional[Union[int, float]] = None) -> Optional[Union[int, float]]:
"""
Validate and convert input to number (int or float).
Returns default if conversion fails.
"""
if x is None:
return default
# Check if already a number type
try:
import numbers
if isinstance(x, numbers.Number):
return x
except:
pass
# Try conversion
try:
# Try int first if it looks like an integer
if isinstance(x, str) and '.' not in x:
return int(x)
return float(x)
except:
return default
def clamp01(x: float) -> float:
"""Clamp value to [0, 1] range."""
return max(0.0, min(1.0, x))
def parse_ratio(r: Optional[str]) -> Optional[float]:
if not r or "/" not in r:
return None
a, b = r.split("/", 1)
try:
den = float(b)
if den == 0:
return None
return float(a) / den
except Exception:
return None
# ===========================
# Utils: ffprobe / ffmpeg
# ===========================
def run_cmd(cmd: List[str]) -> subprocess.CompletedProcess:
p = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')
if p.returncode != 0:
raise RuntimeError(f"Command failed:\n{' '.join(cmd)}\n\nSTDERR:\n{p.stderr.strip()}")
return p
def ffprobe_json(video_path: str) -> Dict[str, Any]:
"""Extract video metadata using ffprobe with validation"""
# Check if file exists
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video file not found: {video_path}")
# Check if file is readable and not empty
file_size = os.path.getsize(video_path)
if file_size == 0:
raise RuntimeError(f"Video file is empty: {video_path}")
cmd = [
"ffprobe", "-v", "error",
"-print_format", "json",
"-show_format", "-show_streams",
video_path
]
try:
out = run_cmd(cmd).stdout
if not out or not out.strip():
raise RuntimeError(f"ffprobe returned empty output for: {video_path}")
return json.loads(out)
except json.JSONDecodeError as e:
raise RuntimeError(f"Failed to parse ffprobe output for {video_path}: {e}")
except Exception as e:
# Check if it's the moov atom error
if "moov atom not found" in str(e).lower():
raise RuntimeError(
f"Invalid or incomplete MP4 file: {video_path}\n\n"
f"The file may be:\n"
f"- Still being created/processed\n"
f"- Corrupted or incomplete\n"
f"- Not properly finalized by ffmpeg\n\n"
f"Please wait for the encoding to complete and try again."
)
raise
def extract_frames_ffmpeg(video_path: str, out_dir: str, every_sec: float, max_frames: int) -> List[Path]:
"""
Extract frames every `every_sec` seconds, up to `max_frames`.
Scale down for faster/robust hashing.
"""
out_pattern = str(Path(out_dir) / "frame_%05d.jpg")
vf = f"fps=1/{every_sec},scale=320:-1"
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-i", video_path,
"-vf", vf,
"-frames:v", str(max_frames),
out_pattern
]
run_cmd(cmd)
frames = sorted(Path(out_dir).glob("frame_*.jpg"))
return frames
def extract_audio_wav(video_path: str, wav_path: str, sr: int = 22050) -> None:
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error",
"-i", video_path,
"-vn",
"-ac", "1",
"-ar", str(sr),
"-f", "wav",
wav_path
]
run_cmd(cmd)
@dataclass
class VideoMeta:
duration: Optional[float]
size: Optional[int]
format_name: Optional[str]
overall_bitrate: Optional[int]
tags: Dict[str, Any]
v_codec: Optional[str]
v_width: Optional[int]
v_height: Optional[int]
v_fps: Optional[float]
v_pix_fmt: Optional[str]
v_bitrate: Optional[int]
v_frame_count: Optional[int] # Added: number of frames
a_codec: Optional[str]
a_sample_rate: Optional[int]
a_channels: Optional[int]
a_bitrate: Optional[int]
def parse_metadata(meta: Dict[str, Any]) -> VideoMeta:
fmt = meta.get("format", {}) or {}
streams = meta.get("streams", []) or []
v = next((s for s in streams if s.get("codec_type") == "video"), None)
a = next((s for s in streams if s.get("codec_type") == "audio"), None)
duration = _to_float(fmt.get("duration"))
size = _to_int(fmt.get("size"))
format_name = fmt.get("format_name")
overall_bitrate = _to_int(fmt.get("bit_rate"))
tags = fmt.get("tags", {}) or {}
v_codec = v.get("codec_name") if v else None
v_width = _to_int(v.get("width")) if v else None
v_height = _to_int(v.get("height")) if v else None
v_fps = parse_ratio((v.get("avg_frame_rate") or v.get("r_frame_rate")) if v else None)
v_pix_fmt = v.get("pix_fmt") if v else None
v_bitrate = _to_int(v.get("bit_rate")) if v else None
# Calculate frame count from nb_frames or duration * fps
v_frame_count = None
if v:
v_frame_count = _to_int(v.get("nb_frames"))
if v_frame_count is None and duration and v_fps:
v_frame_count = int(duration * v_fps)
a_codec = a.get("codec_name") if a else None
a_sample_rate = _to_int(a.get("sample_rate")) if a else None
a_channels = _to_int(a.get("channels")) if a else None
a_bitrate = _to_int(a.get("bit_rate")) if a else None
return VideoMeta(
duration=duration,
size=size,
format_name=format_name,
overall_bitrate=overall_bitrate,
tags=tags,
v_codec=v_codec,
v_width=v_width,
v_height=v_height,
v_fps=v_fps,
v_pix_fmt=v_pix_fmt,
v_bitrate=v_bitrate,
v_frame_count=v_frame_count,
a_codec=a_codec,
a_sample_rate=a_sample_rate,
a_channels=a_channels,
a_bitrate=a_bitrate,
)
def sim_equal(a: Any, b: Any) -> float:
if a is None or b is None:
return 0.0
return 1.0 if a == b else 0.0
def sim_close(a: Optional[float], b: Optional[float], tol_ratio: float) -> float:
"""
Similarity based on relative closeness:
1.0 if within tol_ratio, smoothly decreases.
"""
if a is None or b is None:
return 0.0
if a == 0 and b == 0:
return 1.0
denom = max(abs(a), abs(b), 1e-9)
rel = abs(a - b) / denom
if rel <= tol_ratio:
return 1.0
# decay after tolerance
return max(0.0, 1.0 - (rel - tol_ratio) / (1.0 - tol_ratio))
def metadata_similarity(m1: VideoMeta, m2: VideoMeta) -> Tuple[float, Dict[str, float]]:
"""
Weighted similarity from 0..1.
This is "deep" in the sense of codec/fps/resolution/bitrate/duration/tags.
BUT note: metadata can differ even for same content if re-encoded.
"""
parts: Dict[str, float] = {}
# Core content-ish fields
parts["duration"] = sim_close(m1.duration, m2.duration, tol_ratio=0.02) # 2%
parts["resolution"] = 0.5 * sim_equal(m1.v_width, m2.v_width) + 0.5 * sim_equal(m1.v_height, m2.v_height)
parts["fps"] = sim_close(m1.v_fps, m2.v_fps, tol_ratio=0.03) # 3%
parts["frame_count"] = sim_close(
float(m1.v_frame_count) if m1.v_frame_count else None,
float(m2.v_frame_count) if m2.v_frame_count else None,
tol_ratio=0.03 # 3% tolerance for frame count
)
parts["v_codec"] = sim_equal(m1.v_codec, m2.v_codec)
parts["a_codec"] = sim_equal(m1.a_codec, m2.a_codec)
# Encode-ish fields (help detect exact reupload / same encode profile)
parts["format_name"] = sim_equal(m1.format_name, m2.format_name)
parts["overall_bitrate"] = sim_close(
float(m1.overall_bitrate) if m1.overall_bitrate else None,
float(m2.overall_bitrate) if m2.overall_bitrate else None,
tol_ratio=0.15
)
parts["v_bitrate"] = sim_close(
float(m1.v_bitrate) if m1.v_bitrate else None,
float(m2.v_bitrate) if m2.v_bitrate else None,
tol_ratio=0.20
)
parts["a_bitrate"] = sim_close(
float(m1.a_bitrate) if m1.a_bitrate else None,
float(m2.a_bitrate) if m2.a_bitrate else None,
tol_ratio=0.20
)
parts["sample_rate"] = sim_equal(m1.a_sample_rate, m2.a_sample_rate)
parts["channels"] = sim_equal(m1.a_channels, m2.a_channels)
parts["pix_fmt"] = sim_equal(m1.v_pix_fmt, m2.v_pix_fmt)
parts["size_bytes"] = sim_close(
float(m1.size) if m1.size else None,
float(m2.size) if m2.size else None,
tol_ratio=0.25
)
# Tags: only compare a small, stable subset if present
tag_keys = ["encoder", "major_brand", "minor_version", "compatible_brands", "creation_time"]
tag_hits = 0
tag_total = 0
for k in tag_keys:
v1 = m1.tags.get(k)
v2 = m2.tags.get(k)
if v1 is None or v2 is None:
continue
tag_total += 1
if str(v1) == str(v2):
tag_hits += 1
parts["tags_subset"] = (tag_hits / tag_total) if tag_total else 0.0
# Weights (sum ~ 1.0) - adjusted to include frame_count
weights = {
"duration": 0.14,
"frame_count": 0.08, # New: helps detect trim
"resolution": 0.11,
"fps": 0.07,
"v_codec": 0.05,
"a_codec": 0.04,
"format_name": 0.05,
"overall_bitrate": 0.09,
"v_bitrate": 0.06,
"a_bitrate": 0.05,
"sample_rate": 0.04,
"channels": 0.03,
"pix_fmt": 0.04,
"size_bytes": 0.09,
"tags_subset": 0.06,
}
score = 0.0
for k, w in weights.items():
score += parts.get(k, 0.0) * w
return max(0.0, min(1.0, score)), parts
# -----------------------------
# Visual fingerprint similarity
# -----------------------------
def phash_frames(
video_path: str,
every_sec: float,
max_frames: int,
) -> List[imagehash.ImageHash]:
with tempfile.TemporaryDirectory() as td:
frames = extract_frames_ffmpeg(video_path, td, every_sec=every_sec, max_frames=max_frames)
if not frames:
return []
out: List[imagehash.ImageHash] = []
for fp in frames:
img = Image.open(fp).convert("RGB")
out.append(imagehash.phash(img)) # 64-bit
return out
# -----------------------------
# ORB Feature Matching (Robust to Crop/Resize)
# -----------------------------
def extract_orb_features(video_path: str, num_frames: int = 20, features_per_frame: int = 500) -> List[Tuple[Any, Any]]:
"""
Extract ORB features from sampled frames.
Returns list of (keypoints, descriptors) tuples.
ORB is robust to rotation, scale, and illumination changes.
"""
try:
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
cap.release()
return []
# Sample frames evenly
sample_indices = np.linspace(0, total_frames - 1, min(num_frames, total_frames), dtype=int)
orb = cv2.ORB_create(nfeatures=features_per_frame)
features_list = []
for idx in sample_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if not ret:
continue
# Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect and compute ORB features
keypoints, descriptors = orb.detectAndCompute(gray, None)
if descriptors is not None and len(descriptors) > 0:
features_list.append((keypoints, descriptors))
cap.release()
return features_list
except Exception as e:
print(f"ORB feature extraction failed: {e}")
return []
def orb_similarity(v1: str, v2: str, num_frames: int = 20) -> Tuple[float, Dict[str, Any]]:
"""
Compare videos using ORB feature matching.
Robust to crop, resize, rotation, and watermarks.
Uses feature matching with cross-checking.
"""
features1 = extract_orb_features(v1, num_frames=num_frames)
features2 = extract_orb_features(v2, num_frames=num_frames)
if not features1 or not features2:
return 0.0, {"note": "failed to extract ORB features"}
# Match features between corresponding frames
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
match_ratios = []
for i in range(min(len(features1), len(features2))):
kp1, desc1 = features1[i]
kp2, desc2 = features2[i]
if desc1 is None or desc2 is None:
continue
try:
# Match descriptors
matches = bf.match(desc1, desc2)
if len(matches) > 0:
# Sort by distance (lower = better match)
matches = sorted(matches, key=lambda x: x.distance)
# Good matches: distance < threshold
good_matches = [m for m in matches if m.distance < 50]
# Calculate match ratio
max_features = max(len(desc1), len(desc2))
match_ratio = len(good_matches) / max_features if max_features > 0 else 0.0
match_ratios.append(match_ratio)
except Exception as e:
print(f"Frame {i} matching error: {e}")
continue
if not match_ratios:
return 0.0, {"note": "no valid feature matches"}
# Calculate similarity metrics
avg_match_ratio = float(np.mean(match_ratios))
median_match_ratio = float(np.median(match_ratios))
min_match_ratio = float(np.min(match_ratios))
# Convert match ratio to similarity score
# > 0.3 = very similar (allowing for crops/changes)
# > 0.2 = similar
# > 0.1 = somewhat similar
# < 0.1 = different
if avg_match_ratio >= 0.3:
sim = 0.85 + (avg_match_ratio - 0.3) * 0.5 # 0.85-1.0
elif avg_match_ratio >= 0.2:
sim = 0.65 + (avg_match_ratio - 0.2) * 2.0 # 0.65-0.85
elif avg_match_ratio >= 0.1:
sim = 0.35 + (avg_match_ratio - 0.1) * 3.0 # 0.35-0.65
else:
sim = avg_match_ratio * 3.5 # 0-0.35
return round(clamp01(sim), 2), {
"frames_compared": len(match_ratios),
"avg_match_ratio": round(avg_match_ratio, 3),
"median_match_ratio": round(median_match_ratio, 3),
"min_match_ratio": round(min_match_ratio, 3),
"note": "ORB feature matching (robust to crop/resize/watermark)"
}
# -----------------------------
# CLIP Deep Content Embedding (Advanced)
# -----------------------------
def init_clip_model():
"""Initialize CLIP model (lazy loading) with GPU optimization."""
global CLIP_MODEL, CLIP_PREPROCESS, CLIP_DEVICE
if not CLIP_AVAILABLE:
return False
if CLIP_MODEL is None:
try:
# Multi-GPU support: use the first available GPU or CPU
if torch.cuda.is_available():
CLIP_DEVICE = "cuda"
# For multi-GPU, could use DataParallel
gpu_count = torch.cuda.device_count()
print(f"CUDA available with {gpu_count} GPU(s)")
else:
CLIP_DEVICE = "cpu"
print("CUDA not available, using CPU")
CLIP_MODEL, CLIP_PREPROCESS = clip_module.load("ViT-B/32", device=CLIP_DEVICE)
CLIP_MODEL.eval()
# Enable mixed precision for faster inference on GPU
if CLIP_DEVICE == "cuda":
CLIP_MODEL = CLIP_MODEL.half() # Use FP16
print(f"CLIP model loaded on {CLIP_DEVICE}")
return True
except Exception as e:
print(f"Failed to load CLIP model: {e}")
return False
return True
def extract_clip_embedding(video_path: str, num_frames: int = 10) -> Optional[np.ndarray]:
"""
Extract CLIP embedding from video frames with GPU optimization.
Returns averaged 512D embedding vector.
Extremely robust to crop, resize, watermark, re-encode.
"""
if not init_clip_model():
return None
try:
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
cap.release()
return None
# Sample frames evenly
sample_indices = np.linspace(0, total_frames - 1, min(num_frames, total_frames), dtype=int)
embeddings = []
# Batch processing for GPU efficiency
batch_size = 4 if CLIP_DEVICE == "cuda" else 1
batch_frames = []
for idx in sample_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if not ret:
continue
# Convert BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = Image.fromarray(frame_rgb)
batch_frames.append(image)
# Process batch when full
if len(batch_frames) >= batch_size:
try:
# Stack images into batch
image_tensors = torch.stack([CLIP_PREPROCESS(img) for img in batch_frames]).to(CLIP_DEVICE)
if CLIP_DEVICE == "cuda":
image_tensors = image_tensors.half() # FP16 for speed
with torch.no_grad():
batch_embeddings = CLIP_MODEL.encode_image(image_tensors)
# Normalize
batch_embeddings = batch_embeddings / batch_embeddings.norm(dim=-1, keepdim=True)
embeddings.extend(batch_embeddings.cpu().float().numpy())
batch_frames = []
except Exception as e:
print(f"Batch processing error: {e}")
batch_frames = []
# Process remaining frames
if batch_frames:
try:
image_tensors = torch.stack([CLIP_PREPROCESS(img) for img in batch_frames]).to(CLIP_DEVICE)
if CLIP_DEVICE == "cuda":
image_tensors = image_tensors.half()
with torch.no_grad():
batch_embeddings = CLIP_MODEL.encode_image(image_tensors)
batch_embeddings = batch_embeddings / batch_embeddings.norm(dim=-1, keepdim=True)
embeddings.extend(batch_embeddings.cpu().float().numpy())
except Exception as e:
print(f"Final batch processing error: {e}")
cap.release()
if not embeddings:
return None
# Average embeddings across frames
avg_embedding = np.mean(embeddings, axis=0).astype(np.float32)
# Normalize again
norm = np.linalg.norm(avg_embedding) + 1e-9
return avg_embedding / norm
except Exception as e:
print(f"CLIP embedding extraction failed: {e}")
return None
def clip_similarity(v1: str, v2: str, num_frames: int = 10) -> Tuple[float, Dict[str, Any]]:
"""
Compare videos using CLIP deep embeddings.
Most robust method for detecting same content regardless of:
- Crop, resize, rotation
- Watermarks, logos
- Color grading, filters
- Re-encoding, format changes
- Minor edits
"""
if not CLIP_AVAILABLE:
return 0.0, {"note": "CLIP not available (requires: pip install torch clip)"}
emb1 = extract_clip_embedding(v1, num_frames=num_frames)
emb2 = extract_clip_embedding(v2, num_frames=num_frames)
if emb1 is None or emb2 is None:
return 0.0, {"note": "failed to extract CLIP embeddings"}
# Cosine similarity (already normalized, so just dot product)
cosine = float(np.dot(emb1, emb2))
cosine = max(-1.0, min(1.0, cosine))
# CLIP embeddings are very robust, high cosine = same content
# > 0.95 = identical/near-identical content
# > 0.90 = very similar content
# > 0.80 = similar with modifications
# > 0.70 = somewhat related content
# < 0.70 = different content
if cosine >= 0.95:
sim = 1.0
elif cosine >= 0.90:
sim = 0.9 + (cosine - 0.90) / (0.95 - 0.90) * 0.1
elif cosine >= 0.80:
sim = 0.75 + (cosine - 0.80) / (0.90 - 0.80) * 0.15
elif cosine >= 0.70:
sim = 0.50 + (cosine - 0.70) / (0.80 - 0.70) * 0.25
else:
sim = max(0.0, cosine / 0.70 * 0.5)
return round(clamp01(sim), 2), {
"cosine_similarity": round(cosine, 4),
"frames_analyzed": num_frames,
"embedding_dim": len(emb1),
"method": "CLIP ViT-B/32",
"note": "Deep content embedding (most robust method)"
}
# -----------------------------
# YOLO Logo/Watermark Detection (Advanced)
# -----------------------------
def init_yolo_model():
"""Initialize YOLO model for logo detection (lazy loading)."""
global YOLO_MODEL
if not YOLO_AVAILABLE:
return False
if YOLO_MODEL is None:
try:
# Use YOLOv8n (nano) for fast detection
# For production, train custom model on logo dataset
YOLO_MODEL = YOLO('yolov8n.pt') # Pre-trained COCO model
print("YOLO model loaded for object detection")
return True
except Exception as e:
print(f"Failed to load YOLO model: {e}")
return False
return True
def detect_logos_yolo(video_path: str, num_samples: int = 10, known_logos: Optional[List[str]] = None) -> Dict[str, Any]:
"""
Detect logos/watermarks using YOLOv8.
Args:
video_path: Path to video file
num_samples: Number of frames to sample
known_logos: List of known logo templates (paths to images)
Returns:
Dictionary with logo detection results including:
- detected_objects: List of detected objects with confidence
- logo_regions: Bounding boxes of potential logos
- template_matches: If known_logos provided, template matching results
"""
if not init_yolo_model():
return {"detected": False, "note": "YOLO not available"}
try:
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
cap.release()
return {"detected": False, "note": "no frames"}
# Sample frames
sample_indices = np.linspace(0, total_frames - 1, min(num_samples, total_frames), dtype=int)
all_detections = []
logo_regions = []
for idx in sample_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if not ret:
continue
# Run YOLO detection
results = YOLO_MODEL(frame, verbose=False)
for result in results:
boxes = result.boxes
for box in boxes:
cls = int(box.cls[0])
conf = float(box.conf[0])
xyxy = box.xyxy[0].cpu().numpy()
x1, y1, x2, y2 = xyxy
width = x2 - x1
height = y2 - y1
# Filter for small objects in corners (likely logos)
frame_h, frame_w = frame.shape[:2]
area_percent = (width * height) / (frame_w * frame_h) * 100
# Check if in corner regions
in_corner = (x1 < frame_w * 0.25 or x2 > frame_w * 0.75) and \
(y1 < frame_h * 0.25 or y2 > frame_h * 0.75)
if area_percent < 15 and conf > 0.3: # Small objects with decent confidence
detection = {
"class": cls,
"confidence": round(conf, 3),
"bbox": [int(x1), int(y1), int(x2), int(y2)],
"area_percent": round(area_percent, 2),
"in_corner": in_corner,
"frame": int(idx)
}
all_detections.append(detection)
if in_corner:
logo_regions.append(detection)
cap.release()
# Perform template matching if known logos provided
template_matches = []
if known_logos:
template_matches = match_logo_templates(video_path, known_logos, num_samples)
detected = len(logo_regions) > 0 or len(template_matches) > 0
return {
"detected": detected,
"yolo_detections": len(all_detections),
"logo_regions": logo_regions[:10], # Top 10
"template_matches": template_matches,
"frames_analyzed": len(sample_indices),
"note": "YOLO object detection for logos/watermarks"
}
except Exception as e:
print(f"YOLO logo detection failed: {e}")
return {"detected": False, "note": f"error: {str(e)}"}
def match_logo_templates(video_path: str, template_paths: List[str], num_samples: int = 10) -> List[Dict[str, Any]]:
"""
Match known logo templates in video using OpenCV template matching.
Args:
video_path: Path to video file
template_paths: List of paths to logo template images
num_samples: Number of frames to sample
Returns:
List of template matches with locations and confidence
"""
try:
# Load templates
templates = []
for path in template_paths:
if os.path.exists(path):
template = cv2.imread(path)
if template is not None:
# Convert to grayscale
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
templates.append({
"path": path,
"name": Path(path).stem,
"image": template_gray,
"height": template.shape[0],
"width": template.shape[1]
})
if not templates:
return []
cap = cv2.VideoCapture(video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
cap.release()
return []
sample_indices = np.linspace(0, total_frames - 1, min(num_samples, total_frames), dtype=int)
matches = []
for idx in sample_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
ret, frame = cap.read()
if not ret:
continue
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
for template_info in templates:
template = template_info["image"]
# Multi-scale template matching
scales = [0.5, 0.75, 1.0, 1.25, 1.5]
best_match = None
best_val = -1
for scale in scales:
# Resize template
w = int(template_info["width"] * scale)
h = int(template_info["height"] * scale)
if w > frame_gray.shape[1] or h > frame_gray.shape[0]:
continue
resized_template = cv2.resize(template, (w, h))
# Template matching
result = cv2.matchTemplate(frame_gray, resized_template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
if max_val > best_val:
best_val = max_val
best_match = {
"location": max_loc,
"scale": scale,
"width": w,
"height": h
}
# Accept matches with confidence > 0.6
if best_match and best_val > 0.6:
x, y = best_match["location"]
w, h = best_match["width"], best_match["height"]
matches.append({
"logo_name": template_info["name"],
"confidence": round(best_val, 3),
"bbox": [int(x), int(y), int(x + w), int(y + h)],
"scale": best_match["scale"],
"frame": int(idx)
})
cap.release()
return matches
except Exception as e:
print(f"Template matching failed: {e}")
return []
def logo_detection_similarity(v1: str, v2: str, known_logos: Optional[List[str]] = None) -> Tuple[float, Dict[str, Any]]:
"""
Compare logo/watermark presence between two videos using YOLO and template matching.
Returns:
Similarity score (1.0 = both have same logos, 0.0 = completely different)
"""
logo1 = detect_logos_yolo(v1, num_samples=10, known_logos=known_logos)
logo2 = detect_logos_yolo(v2, num_samples=10, known_logos=known_logos)
detected1 = logo1.get("detected", False)
detected2 = logo2.get("detected", False)
# Both have or both don't have logos
if detected1 == detected2:
if not detected1:
# Both clean
sim = 1.0
note = "No logos detected in either video"
else:
# Both have logos - compare template matches
matches1 = logo1.get("template_matches", [])
matches2 = logo2.get("template_matches", [])
if matches1 and matches2:
# Compare logo names
names1 = set(m["logo_name"] for m in matches1)
names2 = set(m["logo_name"] for m in matches2)
intersection = len(names1 & names2)
union = len(names1 | names2)
if union > 0:
sim = intersection / union
else:
sim = 0.8 # Both have logos but can't compare
note = f"Template match comparison: {intersection}/{union} common logos"
else:
# Use YOLO detections
regions1 = len(logo1.get("logo_regions", []))
regions2 = len(logo2.get("logo_regions", []))
# Similar number of logo regions
if regions1 > 0 and regions2 > 0:
sim = 1.0 - min(abs(regions1 - regions2) / max(regions1, regions2), 0.5)
else:
sim = 0.7
note = f"Logo region comparison: {regions1} vs {regions2} regions"
else:
# One has logos, other doesn't