"""Check a video against the dataset to guess whether it matches something already stored.""" import imagehash import storage from fingerprint import extract_fingerprint # hash_size=8 -> 64-bit phash, so distances range 0-64. DEFAULT_HAMMING_THRESHOLD = 10 DEFAULT_MATCH_RATIO = 0.5 def _hex_to_hash(h: str): return imagehash.hex_to_hash(h) def compare_to_video(query_hashes: list, stored_hashes: list, hamming_threshold: int) -> float: """Fraction of query frames that have a close match somewhere in the stored video.""" if not query_hashes or not stored_hashes: return 0.0 stored_decoded = [_hex_to_hash(f["hash"]) for f in stored_hashes] hits = 0 for qf in query_hashes: qh = _hex_to_hash(qf["hash"]) best = min(qh - sh for sh in stored_decoded) if best <= hamming_threshold: hits += 1 return hits / len(query_hashes) def check_video( query_path: str, hamming_threshold: int = DEFAULT_HAMMING_THRESHOLD, match_ratio_threshold: float = DEFAULT_MATCH_RATIO, samples_per_second: float = 1.0, ) -> dict: query_hashes = extract_fingerprint(query_path, samples_per_second=samples_per_second) candidates = [] for meta in storage.list_videos(): video_id = meta["id"] stored_hashes = storage.load_all_hashes(video_id) ratio = compare_to_video(query_hashes, stored_hashes, hamming_threshold) candidates.append({"id": video_id, "title": meta["title"], "match_ratio": round(ratio, 3)}) candidates.sort(key=lambda c: c["match_ratio"], reverse=True) best = candidates[0] if candidates else None is_match = bool(best and best["match_ratio"] >= match_ratio_threshold) return { "query_path": query_path, "is_likely_copyrighted": is_match, "best_match": best, "top_candidates": candidates[:5], }