125 lines
3.8 KiB
Python
125 lines
3.8 KiB
Python
"""Exact-frame source validation and face-track binding."""
|
|
|
|
import hashlib
|
|
import json
|
|
import subprocess
|
|
from fractions import Fraction
|
|
from pathlib import Path
|
|
|
|
|
|
def digest(path):
|
|
with Path(path).open("rb") as stream:
|
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
|
|
|
|
def probe(path, count):
|
|
args = [
|
|
"ffprobe",
|
|
"-v",
|
|
"error",
|
|
"-show_entries",
|
|
"stream=index,codec_type,width,height,avg_frame_rate,time_base:frame=best_effort_timestamp",
|
|
"-of",
|
|
"json",
|
|
str(path),
|
|
]
|
|
data = json.loads(subprocess.check_output(args, timeout=60))
|
|
streams = data["streams"]
|
|
if len(streams) != 1 or streams[0]["codec_type"] != "video":
|
|
raise ValueError("Selected dialogue video must be silent")
|
|
video = streams[0]
|
|
if (
|
|
Fraction(video["avg_frame_rate"]) != 24
|
|
or not 0 < video["width"] * video["height"] <= 1920 * 1080
|
|
):
|
|
raise ValueError("Expected bounded 24fps video")
|
|
times = [
|
|
int(f["best_effort_timestamp"]) * Fraction(video["time_base"])
|
|
for f in data["frames"]
|
|
]
|
|
if len(times) != count or any(t != Fraction(i, 24) for i, t in enumerate(times)):
|
|
raise ValueError("Missing, duplicated or shifted source samples")
|
|
return video["width"], video["height"]
|
|
|
|
|
|
def read_tracks(path):
|
|
import re
|
|
|
|
path = Path(path)
|
|
with path.open("rb") as stream:
|
|
raw = stream.read(2 * 1024 * 1024 + 1)
|
|
if len(raw) > 2 * 1024 * 1024:
|
|
raise ValueError("Face track record too large")
|
|
if (
|
|
re.fullmatch("[0-9a-f]{64}", path.stem)
|
|
and hashlib.sha256(raw).hexdigest() != path.stem
|
|
):
|
|
raise ValueError("Changed face track asset")
|
|
record = json.loads(raw)
|
|
if not isinstance(record, dict) or record.get("decision") != "pass":
|
|
raise ValueError("Unresolved face tracks")
|
|
tracks = record.get("tracks")
|
|
if not isinstance(tracks, list) or not 1 <= len(tracks) <= 2:
|
|
raise ValueError("Invalid visible face count")
|
|
return record
|
|
|
|
|
|
def target_boxes(record, params, source_sha, width, height):
|
|
if (
|
|
record.get("decision") != "pass"
|
|
or record.get("source_sha256") != source_sha
|
|
or record.get("fps") != 24
|
|
or record.get("num_frames") != params["num_frames"]
|
|
):
|
|
raise ValueError("Face tracks belong to a different source or are unresolved")
|
|
selected = [
|
|
t
|
|
for t in record["tracks"]
|
|
if (t["track_id"], t["speaker_id"])
|
|
== (params["target_track_id"], params["speaker_id"])
|
|
]
|
|
if len(selected) != 1 or len(selected[0]["boxes"]) != params["num_frames"]:
|
|
raise ValueError("Unbound target or incomplete track")
|
|
for box in selected[0]["boxes"]:
|
|
if (
|
|
not isinstance(box, list)
|
|
or len(box) != 4
|
|
or not all(type(x) is int for x in box)
|
|
):
|
|
raise ValueError("Invalid target box")
|
|
x, y, r, b = box
|
|
if not (0 <= x < r <= width and 0 <= y < b <= height):
|
|
raise ValueError("Target outside source")
|
|
return selected[0]["boxes"]
|
|
|
|
|
|
def frames(path, count):
|
|
import cv2
|
|
|
|
cap = cv2.VideoCapture(str(path))
|
|
try:
|
|
for i in range(count):
|
|
ok, frame = cap.read()
|
|
if not ok:
|
|
raise ValueError("Truncated video")
|
|
yield frame
|
|
if cap.read()[0]:
|
|
raise ValueError("Unexpected extra video frames")
|
|
finally:
|
|
cap.release()
|
|
|
|
|
|
def dry_audio(path, count):
|
|
import numpy as np
|
|
import soundfile as sf
|
|
|
|
info = sf.info(path)
|
|
if (
|
|
info.samplerate != 48000
|
|
or info.frames != count * 2000
|
|
or info.channels not in (1, 2)
|
|
):
|
|
raise ValueError("Stem must match the selected 48kHz sample range")
|
|
values, _ = sf.read(path, dtype="float32", always_2d=True)
|
|
return np.mean(values, axis=1)
|