sync project
Browse files- cli.py +42 -0
- fingerprint.py +44 -0
- idgen.py +10 -0
- ingest.py +28 -0
- match.py +56 -0
- requirements.txt +5 -0
- sample_videos/duplicate_reencoded.mp4 +3 -0
- sample_videos/original.mp4 +3 -0
- sample_videos/unrelated.mp4 +3 -0
- scripts/make_test_videos.py +28 -0
- storage.py +139 -0
cli.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import storage
|
| 5 |
+
from ingest import ingest_video
|
| 6 |
+
from match import check_video
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
parser = argparse.ArgumentParser(prog="copyrightgpt", description="Video dataset + copyright match checker")
|
| 11 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 12 |
+
|
| 13 |
+
p_ingest = sub.add_parser("ingest", help="Add a video to the dataset")
|
| 14 |
+
p_ingest.add_argument("path")
|
| 15 |
+
p_ingest.add_argument("--title", default=None)
|
| 16 |
+
p_ingest.add_argument("--rate", type=float, default=1.0, help="samples per second")
|
| 17 |
+
p_ingest.add_argument("--id", default=None, help="append a new patch to this existing video id")
|
| 18 |
+
|
| 19 |
+
p_check = sub.add_parser("check", help="Check a video against the dataset")
|
| 20 |
+
p_check.add_argument("path")
|
| 21 |
+
p_check.add_argument("--rate", type=float, default=1.0, help="samples per second")
|
| 22 |
+
p_check.add_argument("--threshold", type=float, default=0.5, help="match ratio to call it a match (0-1)")
|
| 23 |
+
|
| 24 |
+
sub.add_parser("list", help="List videos in the dataset")
|
| 25 |
+
|
| 26 |
+
args = parser.parse_args()
|
| 27 |
+
|
| 28 |
+
if args.command == "ingest":
|
| 29 |
+
meta = ingest_video(args.path, title=args.title, samples_per_second=args.rate, video_id=args.id)
|
| 30 |
+
print(json.dumps(meta, indent=2))
|
| 31 |
+
|
| 32 |
+
elif args.command == "check":
|
| 33 |
+
result = check_video(args.path, match_ratio_threshold=args.threshold, samples_per_second=args.rate)
|
| 34 |
+
print(json.dumps(result, indent=2))
|
| 35 |
+
|
| 36 |
+
elif args.command == "list":
|
| 37 |
+
for meta in storage.list_videos():
|
| 38 |
+
print(f"{meta['id']} {meta['duration_seconds']:>8.1f}s {meta['total_hashes']:>4} hashes {meta['num_patches']} patch(es) {meta['title']}")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
main()
|
fingerprint.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extract a perceptual-hash fingerprint (sequence of frame hashes) from a video."""
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
import imagehash
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def extract_fingerprint(video_path: str, samples_per_second: float = 1.0, hash_size: int = 8):
|
| 9 |
+
"""Sample frames from a video and compute a perceptual hash for each.
|
| 10 |
+
|
| 11 |
+
Returns a list of {"t": timestamp_seconds, "hash": hex_hash_string}.
|
| 12 |
+
"""
|
| 13 |
+
cap = cv2.VideoCapture(video_path)
|
| 14 |
+
if not cap.isOpened():
|
| 15 |
+
raise ValueError(f"Could not open video: {video_path}")
|
| 16 |
+
|
| 17 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
|
| 18 |
+
frame_interval = max(1, round(fps / samples_per_second))
|
| 19 |
+
|
| 20 |
+
frames = []
|
| 21 |
+
idx = 0
|
| 22 |
+
while True:
|
| 23 |
+
ok, frame = cap.read()
|
| 24 |
+
if not ok:
|
| 25 |
+
break
|
| 26 |
+
if idx % frame_interval == 0:
|
| 27 |
+
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 28 |
+
img = Image.fromarray(rgb)
|
| 29 |
+
h = imagehash.phash(img, hash_size=hash_size)
|
| 30 |
+
frames.append({"t": round(idx / fps, 2), "hash": str(h)})
|
| 31 |
+
idx += 1
|
| 32 |
+
|
| 33 |
+
cap.release()
|
| 34 |
+
return frames
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def video_duration_seconds(video_path: str) -> float:
|
| 38 |
+
cap = cv2.VideoCapture(video_path)
|
| 39 |
+
if not cap.isOpened():
|
| 40 |
+
return 0.0
|
| 41 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
|
| 42 |
+
frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0
|
| 43 |
+
cap.release()
|
| 44 |
+
return round(frame_count / fps, 2) if fps else 0.0
|
idgen.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import base64
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def new_video_id(length: int = 11) -> str:
|
| 6 |
+
"""Generate a YouTube-style random id, e.g. 'dQw4w9WgXcQ'."""
|
| 7 |
+
raw = os.urandom(length)
|
| 8 |
+
b64 = base64.urlsafe_b64encode(raw).decode("ascii")
|
| 9 |
+
b64 = b64.replace("=", "")
|
| 10 |
+
return b64[:length]
|
ingest.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Add a video to the dataset: fingerprint it and store it under an id."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import storage
|
| 6 |
+
from fingerprint import extract_fingerprint, video_duration_seconds
|
| 7 |
+
from idgen import new_video_id
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def ingest_video(source_path: str, title: str | None = None, samples_per_second: float = 1.0, video_id: str | None = None) -> dict:
|
| 11 |
+
"""Ingest a video. Pass video_id to append a new patch to an existing
|
| 12 |
+
entry instead of creating a new one."""
|
| 13 |
+
if not os.path.isfile(source_path):
|
| 14 |
+
raise FileNotFoundError(source_path)
|
| 15 |
+
|
| 16 |
+
fingerprint = extract_fingerprint(source_path, samples_per_second=samples_per_second)
|
| 17 |
+
duration = video_duration_seconds(source_path)
|
| 18 |
+
title = title or os.path.basename(source_path)
|
| 19 |
+
video_id = video_id or new_video_id()
|
| 20 |
+
|
| 21 |
+
meta = storage.add_video_patch(
|
| 22 |
+
video_id=video_id,
|
| 23 |
+
title=title,
|
| 24 |
+
source_path=os.path.abspath(source_path),
|
| 25 |
+
duration_seconds=duration,
|
| 26 |
+
fingerprint=fingerprint,
|
| 27 |
+
)
|
| 28 |
+
return meta
|
match.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Check a video against the dataset to guess whether it matches something already stored."""
|
| 2 |
+
|
| 3 |
+
import imagehash
|
| 4 |
+
|
| 5 |
+
import storage
|
| 6 |
+
from fingerprint import extract_fingerprint
|
| 7 |
+
|
| 8 |
+
# hash_size=8 -> 64-bit phash, so distances range 0-64.
|
| 9 |
+
DEFAULT_HAMMING_THRESHOLD = 10
|
| 10 |
+
DEFAULT_MATCH_RATIO = 0.5
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _hex_to_hash(h: str):
|
| 14 |
+
return imagehash.hex_to_hash(h)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def compare_to_video(query_hashes: list, stored_hashes: list, hamming_threshold: int) -> float:
|
| 18 |
+
"""Fraction of query frames that have a close match somewhere in the stored video."""
|
| 19 |
+
if not query_hashes or not stored_hashes:
|
| 20 |
+
return 0.0
|
| 21 |
+
|
| 22 |
+
stored_decoded = [_hex_to_hash(f["hash"]) for f in stored_hashes]
|
| 23 |
+
hits = 0
|
| 24 |
+
for qf in query_hashes:
|
| 25 |
+
qh = _hex_to_hash(qf["hash"])
|
| 26 |
+
best = min(qh - sh for sh in stored_decoded)
|
| 27 |
+
if best <= hamming_threshold:
|
| 28 |
+
hits += 1
|
| 29 |
+
return hits / len(query_hashes)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def check_video(
|
| 33 |
+
query_path: str,
|
| 34 |
+
hamming_threshold: int = DEFAULT_HAMMING_THRESHOLD,
|
| 35 |
+
match_ratio_threshold: float = DEFAULT_MATCH_RATIO,
|
| 36 |
+
samples_per_second: float = 1.0,
|
| 37 |
+
) -> dict:
|
| 38 |
+
query_hashes = extract_fingerprint(query_path, samples_per_second=samples_per_second)
|
| 39 |
+
|
| 40 |
+
candidates = []
|
| 41 |
+
for meta in storage.list_videos():
|
| 42 |
+
video_id = meta["id"]
|
| 43 |
+
stored_hashes = storage.load_all_hashes(video_id)
|
| 44 |
+
ratio = compare_to_video(query_hashes, stored_hashes, hamming_threshold)
|
| 45 |
+
candidates.append({"id": video_id, "title": meta["title"], "match_ratio": round(ratio, 3)})
|
| 46 |
+
|
| 47 |
+
candidates.sort(key=lambda c: c["match_ratio"], reverse=True)
|
| 48 |
+
best = candidates[0] if candidates else None
|
| 49 |
+
is_match = bool(best and best["match_ratio"] >= match_ratio_threshold)
|
| 50 |
+
|
| 51 |
+
return {
|
| 52 |
+
"query_path": query_path,
|
| 53 |
+
"is_likely_copyrighted": is_match,
|
| 54 |
+
"best_match": best,
|
| 55 |
+
"top_candidates": candidates[:5],
|
| 56 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
opencv-python
|
| 2 |
+
imagehash
|
| 3 |
+
Pillow
|
| 4 |
+
numpy
|
| 5 |
+
huggingface_hub
|
sample_videos/duplicate_reencoded.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3062c3fb8b8c4460fdfdc77cec0017f6cb12286c36853ae7e722c4a8fa6bed57
|
| 3 |
+
size 81142
|
sample_videos/original.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3062c3fb8b8c4460fdfdc77cec0017f6cb12286c36853ae7e722c4a8fa6bed57
|
| 3 |
+
size 81142
|
sample_videos/unrelated.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:39dd37a1c41344ef52d860514977f5d2d82cb21f385ef33c2ee759ab6ab4b02d
|
| 3 |
+
size 81021
|
scripts/make_test_videos.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate a couple of tiny synthetic .mp4 files to smoke-test the pipeline."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
OUT_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "sample_videos")
|
| 9 |
+
os.makedirs(OUT_DIR, exist_ok=True)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def make_video(path, seed, seconds=3, fps=10, size=(160, 120)):
|
| 13 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 14 |
+
writer = cv2.VideoWriter(path, fourcc, fps, size)
|
| 15 |
+
rng = np.random.default_rng(seed)
|
| 16 |
+
base = rng.integers(0, 255, (size[1], size[0], 3), dtype=np.uint8)
|
| 17 |
+
for i in range(seconds * fps):
|
| 18 |
+
frame = base.copy()
|
| 19 |
+
cv2.circle(frame, (20 + (i * 4) % size[0], 60), 10, (0, 0, 255), -1)
|
| 20 |
+
writer.write(frame)
|
| 21 |
+
writer.release()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
make_video(os.path.join(OUT_DIR, "original.mp4"), seed=1)
|
| 26 |
+
make_video(os.path.join(OUT_DIR, "duplicate_reencoded.mp4"), seed=1) # same content
|
| 27 |
+
make_video(os.path.join(OUT_DIR, "unrelated.mp4"), seed=99) # different content
|
| 28 |
+
print("Wrote sample videos to", OUT_DIR)
|
storage.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dataset storage: dataset/<id>/main.bin (metadata) + dataset/<id>/patch-N.dat (fingerprint chunks).
|
| 2 |
+
|
| 3 |
+
Each video gets a folder named by its id (the "bin"). main.bin holds the
|
| 4 |
+
metadata record. Every ingest call writes a new patch-N.dat file holding that
|
| 5 |
+
call's frame hashes, so future re-ingests / additions just add more patch
|
| 6 |
+
files instead of rewriting everything.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import struct
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
|
| 13 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
+
DATASET_DIR = os.path.join(BASE_DIR, "dataset")
|
| 15 |
+
|
| 16 |
+
MAIN_BIN_VERSION = 1
|
| 17 |
+
PATCH_ENTRY = struct.Struct("<fQ") # timestamp (float32), phash (uint64)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _write_str(f, s: str):
|
| 21 |
+
data = s.encode("utf-8")
|
| 22 |
+
f.write(struct.pack("<I", len(data)))
|
| 23 |
+
f.write(data)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _read_str(f) -> str:
|
| 27 |
+
(n,) = struct.unpack("<I", f.read(4))
|
| 28 |
+
return f.read(n).decode("utf-8")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def video_dir(video_id: str) -> str:
|
| 32 |
+
d = os.path.join(DATASET_DIR, video_id)
|
| 33 |
+
os.makedirs(d, exist_ok=True)
|
| 34 |
+
return d
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _main_bin_path(video_id: str) -> str:
|
| 38 |
+
return os.path.join(video_dir(video_id), "main.bin")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def write_main_bin(video_id, title, source_path, duration_seconds, created_at, num_patches, total_hashes):
|
| 42 |
+
with open(_main_bin_path(video_id), "wb") as f:
|
| 43 |
+
f.write(struct.pack("<B", MAIN_BIN_VERSION))
|
| 44 |
+
_write_str(f, video_id)
|
| 45 |
+
_write_str(f, title)
|
| 46 |
+
_write_str(f, source_path)
|
| 47 |
+
f.write(struct.pack("<d", duration_seconds))
|
| 48 |
+
_write_str(f, created_at)
|
| 49 |
+
f.write(struct.pack("<II", num_patches, total_hashes))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def read_main_bin(video_id: str) -> dict:
|
| 53 |
+
with open(_main_bin_path(video_id), "rb") as f:
|
| 54 |
+
f.read(1) # version, unused for now
|
| 55 |
+
vid = _read_str(f)
|
| 56 |
+
title = _read_str(f)
|
| 57 |
+
source_path = _read_str(f)
|
| 58 |
+
(duration,) = struct.unpack("<d", f.read(8))
|
| 59 |
+
created_at = _read_str(f)
|
| 60 |
+
num_patches, total_hashes = struct.unpack("<II", f.read(8))
|
| 61 |
+
return {
|
| 62 |
+
"id": vid,
|
| 63 |
+
"title": title,
|
| 64 |
+
"source_path": source_path,
|
| 65 |
+
"duration_seconds": duration,
|
| 66 |
+
"created_at": created_at,
|
| 67 |
+
"num_patches": num_patches,
|
| 68 |
+
"total_hashes": total_hashes,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def list_patch_files(video_id: str) -> list:
|
| 73 |
+
d = video_dir(video_id)
|
| 74 |
+
files = [fn for fn in os.listdir(d) if fn.startswith("patch-") and fn.endswith(".dat")]
|
| 75 |
+
files.sort(key=lambda fn: int(fn[len("patch-"):-len(".dat")]))
|
| 76 |
+
return [os.path.join(d, fn) for fn in files]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def write_patch(video_id: str, patch_index: int, fingerprint: list) -> str:
|
| 80 |
+
path = os.path.join(video_dir(video_id), f"patch-{patch_index}.dat")
|
| 81 |
+
with open(path, "wb") as f:
|
| 82 |
+
f.write(struct.pack("<I", len(fingerprint)))
|
| 83 |
+
for entry in fingerprint:
|
| 84 |
+
f.write(PATCH_ENTRY.pack(entry["t"], int(entry["hash"], 16)))
|
| 85 |
+
return path
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def read_patch(path: str) -> list:
|
| 89 |
+
entries = []
|
| 90 |
+
with open(path, "rb") as f:
|
| 91 |
+
(count,) = struct.unpack("<I", f.read(4))
|
| 92 |
+
for _ in range(count):
|
| 93 |
+
t, h = PATCH_ENTRY.unpack(f.read(PATCH_ENTRY.size))
|
| 94 |
+
entries.append({"t": t, "hash": format(h, "016x")})
|
| 95 |
+
return entries
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def load_all_hashes(video_id: str) -> list:
|
| 99 |
+
hashes = []
|
| 100 |
+
for p in list_patch_files(video_id):
|
| 101 |
+
hashes.extend(read_patch(p))
|
| 102 |
+
return hashes
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def add_video_patch(video_id, title, source_path, duration_seconds, fingerprint) -> dict:
|
| 106 |
+
"""Write a new patch file for this id and refresh main.bin. Works for both
|
| 107 |
+
brand-new ids and appending more fingerprint data to an existing id."""
|
| 108 |
+
next_index = len(list_patch_files(video_id))
|
| 109 |
+
write_patch(video_id, next_index, fingerprint)
|
| 110 |
+
|
| 111 |
+
total_hashes = sum(len(read_patch(p)) for p in list_patch_files(video_id))
|
| 112 |
+
created_at = datetime.now(timezone.utc).isoformat()
|
| 113 |
+
write_main_bin(
|
| 114 |
+
video_id=video_id,
|
| 115 |
+
title=title,
|
| 116 |
+
source_path=source_path,
|
| 117 |
+
duration_seconds=duration_seconds,
|
| 118 |
+
created_at=created_at,
|
| 119 |
+
num_patches=next_index + 1,
|
| 120 |
+
total_hashes=total_hashes,
|
| 121 |
+
)
|
| 122 |
+
return read_main_bin(video_id)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def list_videos() -> list:
|
| 126 |
+
if not os.path.isdir(DATASET_DIR):
|
| 127 |
+
return []
|
| 128 |
+
results = []
|
| 129 |
+
for vid in sorted(os.listdir(DATASET_DIR)):
|
| 130 |
+
if os.path.isfile(os.path.join(DATASET_DIR, vid, "main.bin")):
|
| 131 |
+
results.append(read_main_bin(vid))
|
| 132 |
+
return results
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_video(video_id: str):
|
| 136 |
+
try:
|
| 137 |
+
return read_main_bin(video_id)
|
| 138 |
+
except FileNotFoundError:
|
| 139 |
+
return None
|