tinydeskoutstanding-guides / scripts /profile_clips.py
conan123's picture
Add v10 clip profiling scripts
06f8058 verified
Raw History Blame Contribute Delete
3.79 kB
#!/usr/bin/env python3
"""profile_clips.py - per-second signal profile of the public sample clips on tinydeskoutstanding.video.
For every whole second of every clip: mean luma, mean saturation, motion (mean absolute
difference between consecutive frames), audio RMS in dBFS, plus clip-level stream facts and
where the reference soundtrack lines up. Writes JSON Lines to stdout.
Usage: python3 profile_clips.py labels.json samples_dir reference_file > out.jsonl"""
import hashlib, json, os, subprocess, sys
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from soundtrack_match import load, onset_envelope, best_offset # scripts/soundtrack_match.py
W, H = 72, 128 # analysis size; small is enough for luma/saturation/motion averages
BASE = "https://tinydeskoutstanding.video"
def stream_facts(path):
out = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-of", "json", path],
capture_output=True, text=True, check=True).stdout
st = json.loads(out)["streams"]
v = next(s for s in st if s["codec_type"] == "video")
a = next(s for s in st if s["codec_type"] == "audio")
num, den = map(int, v["avg_frame_rate"].split("/"))
return {"width": v["width"], "height": v["height"], "fps": num / den,
"video_duration_s": round(float(v["duration"]), 3),
"audio_duration_s": round(float(a["duration"]), 3),
"audio_sample_rate": int(a["sample_rate"])}
def frames(path):
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", f"scale={W}:{H}",
"-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
capture_output=True, check=True).stdout
return np.frombuffer(raw, np.uint8).reshape(-1, H, W, 3).astype(np.float32) / 255.0
def per_second(path, fps):
f = frames(path)
luma = (0.2126 * f[..., 0] + 0.7152 * f[..., 1] + 0.0722 * f[..., 2]).mean(axis=(1, 2))
mx, mn = f.max(axis=3), f.min(axis=3)
sat = np.where(mx > 0, (mx - mn) / np.maximum(mx, 1e-6), 0).mean(axis=(1, 2))
motion = np.concatenate([[0.0], np.abs(np.diff(f, axis=0)).mean(axis=(1, 2, 3))])
audio = load(path) # 8 kHz mono float32
rows, fps_i = [], round(fps)
for sec in range(int(len(f) // fps_i)):
sl = slice(sec * fps_i, (sec + 1) * fps_i)
a = audio[sec * 8000:(sec + 1) * 8000]
rms = float(np.sqrt((a ** 2).mean())) if len(a) else 0.0
rows.append({"second": sec,
"luma_mean": round(float(luma[sl].mean()), 4),
"saturation_mean": round(float(sat[sl].mean()), 4),
"motion_mean": round(float(motion[sl].mean()), 4),
"motion_max": round(float(motion[sl].max()), 4),
"audio_rms_dbfs": round(20 * np.log10(rms + 1e-9), 1)})
return rows
if __name__ == "__main__":
labels, folder, ref_path = json.load(open(sys.argv[1])), sys.argv[2], sys.argv[3]
ref_env = onset_envelope(load(ref_path))
measured_at = os.environ.get("MEASURED_AT", "")
for src, label in labels.items():
path = os.path.join(folder, os.path.basename(src))
sha = hashlib.sha256(open(path, "rb").read()).hexdigest()
facts = stream_facts(path)
lag, peak = best_offset(ref_env, onset_envelope(load(path)))
clip = {"clip_id": sha[:12], "sha256": sha, "source_url": BASE + src,
"site_label": label, "is_reference": os.path.abspath(path) == os.path.abspath(ref_path),
**facts, "soundtrack_offset_s": round(lag, 2), "soundtrack_match": round(peak, 2),
"measured_at": measured_at}
for r in per_second(path, facts["fps"]):
print(json.dumps({**clip, **r}, ensure_ascii=False))