File size: 4,484 Bytes
10bc78d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dataset storage: dataset/<id>/main.bin (metadata) + dataset/<id>/patch-N.dat (fingerprint chunks).

Each video gets a folder named by its id (the "bin"). main.bin holds the
metadata record. Every ingest call writes a new patch-N.dat file holding that
call's frame hashes, so future re-ingests / additions just add more patch
files instead of rewriting everything.
"""

import os
import struct
from datetime import datetime, timezone

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATASET_DIR = os.path.join(BASE_DIR, "dataset")

MAIN_BIN_VERSION = 1
PATCH_ENTRY = struct.Struct("<fQ")  # timestamp (float32), phash (uint64)


def _write_str(f, s: str):
    data = s.encode("utf-8")
    f.write(struct.pack("<I", len(data)))
    f.write(data)


def _read_str(f) -> str:
    (n,) = struct.unpack("<I", f.read(4))
    return f.read(n).decode("utf-8")


def video_dir(video_id: str) -> str:
    d = os.path.join(DATASET_DIR, video_id)
    os.makedirs(d, exist_ok=True)
    return d


def _main_bin_path(video_id: str) -> str:
    return os.path.join(video_dir(video_id), "main.bin")


def write_main_bin(video_id, title, source_path, duration_seconds, created_at, num_patches, total_hashes):
    with open(_main_bin_path(video_id), "wb") as f:
        f.write(struct.pack("<B", MAIN_BIN_VERSION))
        _write_str(f, video_id)
        _write_str(f, title)
        _write_str(f, source_path)
        f.write(struct.pack("<d", duration_seconds))
        _write_str(f, created_at)
        f.write(struct.pack("<II", num_patches, total_hashes))


def read_main_bin(video_id: str) -> dict:
    with open(_main_bin_path(video_id), "rb") as f:
        f.read(1)  # version, unused for now
        vid = _read_str(f)
        title = _read_str(f)
        source_path = _read_str(f)
        (duration,) = struct.unpack("<d", f.read(8))
        created_at = _read_str(f)
        num_patches, total_hashes = struct.unpack("<II", f.read(8))
    return {
        "id": vid,
        "title": title,
        "source_path": source_path,
        "duration_seconds": duration,
        "created_at": created_at,
        "num_patches": num_patches,
        "total_hashes": total_hashes,
    }


def list_patch_files(video_id: str) -> list:
    d = video_dir(video_id)
    files = [fn for fn in os.listdir(d) if fn.startswith("patch-") and fn.endswith(".dat")]
    files.sort(key=lambda fn: int(fn[len("patch-"):-len(".dat")]))
    return [os.path.join(d, fn) for fn in files]


def write_patch(video_id: str, patch_index: int, fingerprint: list) -> str:
    path = os.path.join(video_dir(video_id), f"patch-{patch_index}.dat")
    with open(path, "wb") as f:
        f.write(struct.pack("<I", len(fingerprint)))
        for entry in fingerprint:
            f.write(PATCH_ENTRY.pack(entry["t"], int(entry["hash"], 16)))
    return path


def read_patch(path: str) -> list:
    entries = []
    with open(path, "rb") as f:
        (count,) = struct.unpack("<I", f.read(4))
        for _ in range(count):
            t, h = PATCH_ENTRY.unpack(f.read(PATCH_ENTRY.size))
            entries.append({"t": t, "hash": format(h, "016x")})
    return entries


def load_all_hashes(video_id: str) -> list:
    hashes = []
    for p in list_patch_files(video_id):
        hashes.extend(read_patch(p))
    return hashes


def add_video_patch(video_id, title, source_path, duration_seconds, fingerprint) -> dict:
    """Write a new patch file for this id and refresh main.bin. Works for both
    brand-new ids and appending more fingerprint data to an existing id."""
    next_index = len(list_patch_files(video_id))
    write_patch(video_id, next_index, fingerprint)

    total_hashes = sum(len(read_patch(p)) for p in list_patch_files(video_id))
    created_at = datetime.now(timezone.utc).isoformat()
    write_main_bin(
        video_id=video_id,
        title=title,
        source_path=source_path,
        duration_seconds=duration_seconds,
        created_at=created_at,
        num_patches=next_index + 1,
        total_hashes=total_hashes,
    )
    return read_main_bin(video_id)


def list_videos() -> list:
    if not os.path.isdir(DATASET_DIR):
        return []
    results = []
    for vid in sorted(os.listdir(DATASET_DIR)):
        if os.path.isfile(os.path.join(DATASET_DIR, vid, "main.bin")):
            results.append(read_main_bin(vid))
    return results


def get_video(video_id: str):
    try:
        return read_main_bin(video_id)
    except FileNotFoundError:
        return None