copyrightgpt-v1 / storage.py
hdcli's picture
sync project
10bc78d verified
Raw History Blame Contribute Delete
4.48 kB
"""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