joemaddalone's picture
Upload scripts/audit.py with huggingface_hub
d2b2537 verified
Raw History Blame Contribute Delete
24.3 kB
#!/usr/bin/env python3
"""Step 1 audit of burak29/Natural_Language_to_Ffmpeg_Commands.
Loads the parquet export, deduplicates exact and near-duplicate pairs,
builds tiny synthetic media for every input filename a command references,
runs each command in an isolated temp dir, static-validates the rest
(hardware/network commands), and labels every row: runs | static-only | fails.
Outputs (in /work/out):
audit_table.csv one row per source row: id, label, category, dup_of, notes, reason
report.json counts, failing examples, suspicious rows
Prints a summary at the end.
"""
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import difflib
from collections import Counter, defaultdict
from urllib.request import urlopen
PARQUET_URL = ("https://huggingface.co/datasets/burak29/Natural_Language_to_Ffmpeg_Commands/"
"resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet")
OUT = "/work/out"
MEDIA = "/work/media"
os.makedirs(OUT, exist_ok=True)
os.makedirs(MEDIA, exist_ok=True)
import pandas as pd # noqa: E402
# ---------------------------------------------------------------- helpers
VIDEO_EXT = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".m4v", ".mpg", ".mpeg", ".ts", ".wmv", ".3gp"}
AUDIO_EXT = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg", ".opus", ".wma", ".aiff", ".amr"}
IMAGE_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tiff", ".tif", ".ppm", ".pgm", ".pam"}
SUB_EXT = {".srt", ".ass", ".ssa", ".vtt", ".ttml"}
LAVFI_SOURCES = {"testsrc", "testsrc2", "sine", "color", "anullsrc", "mandelbrot",
"smptebars", "smptehdbars", "rgbtestsrc", "life", "cellauto", "haldclutsrc",
"nullsrc", "gradients", "qrencodesrc", "zeroes", "srtpacketsrc", "vignette"}
STATIC_ONLY_MARKERS = [
"nvenc", "qsv", "v4l2", "rtsp", "srt:", "udp:", "rtp:", "videotoolbox", "vaapi",
"d3d11va", "dxva2", "mediacodec", "cuda", "cuvid", "mmal", "omx",
"dshow", "avfoundation", "x11grab", "gdigrab", ":video=", ":audio=",
]
# options that do NOT take a separate value token
NO_VALUE_OPTS = {"-y", "-n", "-vn", "-an", "-sn", "-dn", "-ignore_unknown", "-copyts",
"-shortest", "-nostdin", "-ss", # placeholder; real set below
"-map_chapters", "-noautorotate"}
# options that DO take a value (subset covering our data; unknown -xxx with a
# following non-dash token is treated as taking a value too)
VALUE_OPTS = {"-i", "-f", "-ss", "-to", "-t", "-c", "-c:v", "-c:a", "-c:s", "-c:d", "-c:data",
"-vf", "-af", "-map", "-b", "-b:v", "-b:a", "-filter_complex", "-filter_complex_script",
"-r", "-s", "-ar", "-ac", "-pix_fmt", "-vcodec", "-acodec", "-scodec",
"-metadata", "-profile:v", "-profile:a", "-profile", "-level", "-preset", "-crf",
"-q", "-q:v", "-q:a", "-aspect", "-frames", "-frames:v", "-frames:a",
"-itsoffset", "-tune", "-x264-params", "-movflags", "-flags", "-hwaccel",
"-sample_fmt", "-channel_layout", "-rc", "-g", "-keyint_min", "-sc_threshold",
"-maxrate", "-bufsize", "-hls_time", "-hls_playlist_type", "-hls_segment_filename",
"-update", "-loop", "-segment_time", "-fmp4", "-acodec", "-vtag", "-atag",
"-dcodec", "-cutoff", "-vol", "-tempo", "-pitch", "-metadata:s"}
TOKEN_RE = re.compile(r"[A-Za-z0-9_.%:\-/\\]+\.(?:[A-Za-z0-9]{1,6})(?![\w=\-.]*[A-Za-z0-9]\s*=)|"
r"[A-Za-z0-9_\-]+(?:%0?\d+d)[A-Za-z0-9_.]*")
def shlex_ok(cmd):
try:
return shlex.split(cmd)
except ValueError:
return None
def parse_tokens(cmd):
"""Return (inputs, outputs, tokens) using a value-taking-option heuristic."""
toks = shlex_ok(cmd)
if toks is None:
return [], [], []
positionals = []
i = 1 # skip 'ffmpeg'
while i < len(toks):
t = toks[i]
if t.startswith("-") and not re.fullmatch(r"-[\d.]+", t):
base = t.split("=")[0]
takes_val = (base in VALUE_OPTS) or (base not in NO_VALUE_OPTS
and i + 1 < len(toks) and not toks[i + 1].startswith("-"))
if takes_val and base != "-i":
i += 2
continue
i += 1
continue
positionals.append(t)
i += 1
if len(positionals) <= 1:
return positionals, positionals, toks # ambiguous
return positionals[:-1], positionals[-1:], toks
def is_lavfi_source(tok):
head = tok.split("=")[0].split(":")[0]
return head in LAVFI_SOURCES
def ext_of(fn):
m = re.search(r"\.([A-Za-z0-9]{1,6})$", fn)
return ("." + m.group(1).lower()) if m else ""
# filter options that take a filename argument inside -vf/-af/filter_complex values
FILTER_FILE_RE = re.compile(
r"(?:subtitles|ass)=([^:'\"\s]+\.(?:srt|ass|ssa|vtt))|"
r"(?:textfile|fontfile|filename)=([\w./\-]+\.\w+)")
def filter_embedded_files(cmd):
"""Filenames referenced inside filter arguments (subtitles=, textfile=...)."""
files = []
for m in re.finditer(r"-v(?:f)?\s+(?:(['\"])(.*?)\1|(\S+))|-af\s+(?:(['\"])(.*?)\4|(\S+))|"
r"-filter_complex\s+(?:(['\"])(.*?)\7|(\S+))", cmd):
chain = next((g for g in m.groups() if g), "")
for m2 in FILTER_FILE_RE.finditer(chain):
files.append(m2.group(1) or m2.group(2))
return files
def is_sequence(fn):
return bool(re.search(r"%0?\d*d", fn))
def is_glob(fn):
return bool(re.search(r"[\*\?]", fn))
def seq_dir(fn):
"""directory part of a sequence/glob pattern"""
return os.path.dirname(fn) or "."
def make_input_file(path, is_concat=False):
"""Create a tiny synthetic media file at `path` based on its extension."""
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
ext = ext_of(path)
try:
# .txt referenced by -f concat: write a real concat list pointing at a
# small video that must also exist in the pool
if ext == ".txt" and is_concat:
target = os.path.join(MEDIA, "video.mp4")
if not os.path.exists(target):
if not make_input_file(target):
return False
with open(path, "w") as f:
f.write("file 'video.mp4'\n")
return os.path.exists(path)
if is_glob(path):
d = seq_dir(path)
os.makedirs(d, exist_ok=True)
e = ext_of(path) or ".jpg"
for k in range(1, 4):
run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi",
"-i", "testsrc=size=64x64:rate=1", "-frames:v", "1",
os.path.join(d, f"synthimg_{k:03d}{e}")], 15)
return len(os.listdir(d)) >= 3
if ext in SUB_EXT or ext == ".txt":
with open(path, "w") as f:
f.write("1\n00:00:00,000 --> 00:00:00,500\nhello world\n\nsample text\n")
return os.path.exists(path)
if is_sequence(path) or ext in IMAGE_EXT:
args = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi",
"-i", "testsrc=duration=0.5:size=64x64:rate=5"]
if is_sequence(path):
args.append(path)
else:
args += ["-frames:v", "1", path]
run(args, 15)
if is_sequence(path):
d = seq_dir(path)
base = re.sub(r"%0?\d*d", "*", os.path.basename(path))
import glob as _g
return len(_g.glob(os.path.join(d, base))) >= 1
return os.path.exists(path)
if ext in AUDIO_EXT:
run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=1:frequency=440",
"-ar", "44100", "-ac", "1", path], 15)
return True
if ext in (".mpg", ".mpeg"):
# mpeg muxer needs mpeg2 codecs; default h264 selection fails
run(["ffmpeg", "-v", "error", "-y",
"-f", "lavfi", "-i", "testsrc=duration=12:size=640x480:rate=10",
"-f", "lavfi", "-i", "sine=duration=12",
"-map", "0:v", "-map", "1:a", "-c:v", "mpeg2video", "-c:a", "mp2",
"-pix_fmt", "yuvj420p", path], 60)
return os.path.exists(path)
if ext == ".opus":
run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=duration=3",
"-c:a", "libopus", path], 30)
return os.path.exists(path)
if ext in VIDEO_EXT or ext == "":
# 12s / 640x480 full-range video with audio (and a subtitle stream where
# the container supports one), so seeks, crops, tile grids, -map 0:s and
# jpeg extraction have real targets. yuvj420p so mjpeg output works.
sub_fmt = {".mp4": "mov_text", ".m4v": "mov_text", ".mov": "mov_text",
".mkv": "srt", ".webm": "webvtt"}.get(ext)
srt = os.path.join(MEDIA, "_synth.srt")
with open(srt, "w") as f:
f.write("1\n00:00:00,000 --> 00:00:11,500\nhello world\n\n2\n"
"00:00:05,000 --> 00:00:11,500\nsecond line\n\n")
args = ["ffmpeg", "-v", "error", "-y",
"-f", "lavfi", "-i", "testsrc=duration=12:size=640x480:rate=10",
"-f", "lavfi", "-i", "sine=duration=12:frequency=440"]
maps = ["-map", "0:v", "-map", "1:a"]
if sub_fmt:
args += ["-i", srt]
maps += ["-map", "2:s", "-c:s", sub_fmt]
args += maps + ["-pix_fmt", "yuvj420p", "-shortest", path]
run(args, 60)
return os.path.exists(path)
return False
except Exception:
return False
def run(cmd, timeout):
return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
def static_validate(cmd, toks):
"""Check filters/encoders exist. Returns list of failure reasons (empty = OK)."""
problems = []
text = " ".join(toks)
# filters from -vf / -af / filter_complex
filters = set()
for m in re.finditer(r"(?:-vf|-af|-filter_complex)\s+(?:(['\"])(.*?)\1|(\S+))", text):
chain = m.group(2) or m.group(3) or ""
for part in re.split(r"[,;]", chain):
name = part.strip().split("=")[0].split("[")[0].strip()
if name:
filters.add(name)
for f in sorted(filters):
p = run(["ffmpeg", "-hide_banner", "-h", f"filter={f}"], 10)
if p.returncode != 0 or b"Unknown filter" in p.stderr:
problems.append(f"filter not found: {f}")
# encoders from -c:v/-c:a/-vcodec/-acodec
for m in re.finditer(r"(?:-c:v|-c:a|-vcodec|-acodec)\s+(\S+)", text):
enc = m.group(1)
if enc in ("copy", "none"):
continue
p = run(["ffmpeg", "-hide_banner", "-encoders"], 10)
names = p.stdout.decode(errors="replace")
if enc not in names:
problems.append(f"encoder not found: {enc}")
# muxer from output extension
outs, _, _ = parse_tokens(cmd)
for o in outs:
ext = ext_of(o)
if not ext:
continue
p = run(["ffmpeg", "-hide_banner", "-muxers"], 10)
if p.returncode != 0:
problems.append("could not list muxers")
continue
names = p.stdout.decode(errors="replace") + p.stderr.decode(errors="replace")
# approximate: extension's common muxer name
guess = {"mp4": "mp4", "mkv": "matroska", "gif": "gif", "mp3": "mp3", "wav": "wav",
"webm": "webm", "avi": "avi", "mov": "mov", "flv": "flv", "m4a": "ipod",
"aac": "aac", "flac": "flac", "srt": "srt", "ass": "ass", "ts": "mpegts",
"m3u8": "hls", "jpg": "image2", "jpeg": "image2", "png": "image2"}.get(ext[1:], ext[1:])
if guess not in names.lower():
problems.append(f"muxer unclear for .{ext[1:]} (guess={guess})")
return problems
def suspicious(cmd, inputs):
"""Semantic red flags that still run: second -af/-vf overriding, bad -map."""
flags = []
toks = shlex_ok(cmd) or []
for opt in ("-vf", "-af"):
if sum(1 for t in toks if t == opt) > 1:
flags.append(f"duplicate {opt} (second overrides first)")
if sum(1 for t in toks if t == "-map") >= 2 and len(inputs) == 1 and not any(is_lavfi_source(x) for x in inputs):
if any(re.fullmatch(r"[1-9]\d*:[avs]\S*", t) for t in toks):
flags.append("-map references input index >= 1 with only one real input")
return flags
def classify(cmd):
toks = shlex_ok(cmd) or []
text = " ".join(toks)
if any(m in text for m in ("rtsp", "udp:", "rtp:", "srt:", "http://", "https://", "m3u8", "-hls")):
return "streaming"
if "concat" in text or "-f concat" in text:
return "concat"
if "-ss" in toks or "-to" in toks or (" -t " in text):
return "trim"
if "-af" in toks:
return "audio filter"
if "-vf" in toks or "filter_complex" in text:
return "video filter"
return "conversion"
def norm(s):
s = s.lower()
s = re.sub(r"\s+", " ", s).strip()
s = s.replace('"', "'")
return s
def sim(a, b):
return difflib.SequenceMatcher(None, a, b).ratio()
# ---------------------------------------------------------------- load data
print("loading parquet ...", flush=True)
with tempfile.NamedTemporaryFile(suffix=".parquet", delete=False) as tf:
with urlopen(PARQUET_URL, timeout=60) as r:
tf.write(r.read())
tmp_path = tf.name
df = pd.read_parquet(tmp_path)
assert set(df.columns) == {"natural_language", "ffmpeg_command"}, df.columns
print(f"rows: {len(df)}", flush=True)
# ---------------------------------------------------------------- dedup
records = df.to_dict("records")
for i, r in enumerate(records):
r["id"] = i
r["_nl"] = norm(r["natural_language"])
r["_cmd"] = norm(r["ffmpeg_command"])
kept, dup_of = [], {}
by_exact = {}
for r in records:
key = (r["_nl"], r["_cmd"])
if key in by_exact:
dup_of[r["id"]] = by_exact[key]
r["label"] = "dup"
else:
by_exact[key] = r["id"]
kept.append(r)
# near-duplicates among kept: high prompt AND command similarity
near_dropped = 0
for i in range(len(kept)):
if kept[i].get("label") == "dup":
continue
for j in range(i + 1, len(kept)):
if kept[j].get("label") == "dup":
continue
if sim(kept[i]["_nl"], kept[j]["_nl"]) >= 0.90 and sim(kept[i]["_cmd"], kept[j]["_cmd"]) >= 0.90:
dup_of[kept[j]["id"]] = kept[i]["id"]
kept[j]["label"] = "dup"
near_dropped += 1
unique = [r for r in kept if r.get("label") != "dup"]
print(f"unique rows after dedup: {len(unique)} (exact dups: {len(records)-len(kept)}, near dups: {near_dropped})", flush=True)
# ---------------------------------------------------------------- media pool
print("building media pool ...", flush=True)
all_inputs = defaultdict(list) # filename -> [ids]
for r in unique:
ins, _, _ = parse_tokens(r["ffmpeg_command"])
refs = list(ins) + filter_embedded_files(r["ffmpeg_command"])
for fn in refs:
if not fn or fn.startswith("-"):
continue
if is_lavfi_source(fn):
continue
# skip option-like tokens (e.g. 'strength=0.2' from a malformed filter)
if "." not in fn and "%" not in fn and "*" not in fn and "/" not in fn:
continue
if ":" in fn:
continue # lavfi source args or protocol-ish tokens; not file inputs
all_inputs[fn].append(r["id"])
print(f"distinct input filenames: {len(all_inputs)}", flush=True)
made = {}
for gi, fn in enumerate(sorted(all_inputs)):
# concat lists need command context to write a real list file
is_concat = False
for r in unique:
if fn in list(parse_tokens(r["ffmpeg_command"])[0]) + \
filter_embedded_files(r["ffmpeg_command"]):
if "-f concat" in r["ffmpeg_command"]:
is_concat = True
break
if is_glob(fn) or is_sequence(fn):
# own dir per pattern: avoids sanitized-name collisions and keeps
# the sequence/glob frames isolated for the runner to copy
path = os.path.join(MEDIA, f"_pat_{gi}", os.path.basename(fn))
else:
path = os.path.join(MEDIA, re.sub(r"[^\w.\-]", "_", fn))
ok = make_input_file(path, is_concat=is_concat)
made[fn] = path if ok else None
if not ok:
print(f" could not create input for: {fn}", flush=True)
print(f"media files created: {sum(1 for v in made.values() if v)} / {len(all_inputs)}", flush=True)
# ---------------------------------------------------------------- run / static
results = {}
for k, r in enumerate(unique):
rid = r["id"]
cmd = r["ffmpeg_command"]
toks = shlex_ok(cmd)
label, reason, notes = None, "", []
if toks is None:
label = "fails"
reason = "unparseable quoting"
else:
text = " ".join(toks)
static_markers = [m for m in STATIC_ONLY_MARKERS if m in text]
ins, outs, _ = parse_tokens(cmd)
real_inputs = [x for x in ins if x and not x.startswith("-") and not is_lavfi_source(x)]
real_inputs += [f for f in filter_embedded_files(cmd) if f not in real_inputs]
missing_inputs = [x for x in real_inputs if x not in made or made[x] is None]
if static_markers:
probs = static_validate(cmd, toks)
if probs:
label, reason = "fails", "static: " + "; ".join(probs)
else:
label = "static-only"
reason = "hardware/network: " + ",".join(sorted(set(static_markers)))
elif missing_inputs:
probs = static_validate(cmd, toks)
if probs:
label, reason = "fails", "static: " + "; ".join(probs)
else:
label = "static-only"
reason = "input not creatable: " + ",".join(missing_inputs[:3])
else:
# run it
with tempfile.TemporaryDirectory(dir="/tmp") as td:
try:
for fn in real_inputs:
if is_sequence(fn) or is_glob(fn):
# copy the pattern's own dir into cwd, keeping structure
src_dir = os.path.dirname(made[fn])
d = seq_dir(fn)
os.makedirs(os.path.join(td, d), exist_ok=True)
for f in os.listdir(src_dir):
shutil.copy(os.path.join(src_dir, f), os.path.join(td, d, os.path.basename(f)))
else:
dst = os.path.join(td, os.path.basename(fn))
if os.path.abspath(made[fn]) != os.path.abspath(dst):
shutil.copy(made[fn], dst)
# run the ORIGINAL command string: re-tokenizing destroys
# quote semantics inside filter args (drawtext x='...')
p = run(["/bin/sh", "-lc", f"cd {td} && timeout 10 {cmd}"], 15)
if p.returncode == 0:
label = "runs"
notes = suspicious(cmd, real_inputs)
else:
label = "fails"
err = p.stderr.decode(errors="replace").strip().splitlines()
reason = err[-1] if err else f"exit {p.returncode}"
except subprocess.TimeoutExpired:
if any(h in cmd for h in ("minterpolate", "loop=loop=-1", "framerate=240", "fps=240")):
label = "static-only"
reason = "too slow for sandbox (heavy/infinite filter)"
else:
label = "fails"
reason = "timeout > 10s"
except Exception as e:
label = "fails"
reason = f"harness error: {e}"
results[rid] = {"label": label, "reason": reason[:400], "notes": notes, "category": classify(cmd)}
# ------------------------------------------------- build-limitation reclass
# a failure caused by a codec/filter absent from THIS build is an environment
# limitation, not a bad command: static-only
ENC_LIST = run(["ffmpeg", "-hide_banner", "-encoders"], 10).stdout.decode(errors="replace")
def filter_exists(name):
p = run(["ffmpeg", "-hide_banner", "-h", f"filter={name}"], 10)
return p.returncode == 0 and b"Unknown filter" not in p.stderr
def cmd_filters(cmd):
out = set()
for m in re.finditer(r"-v(?:f)?\s+(?:(['\"])(.*?)\1|(\S+))|-af\s+(?:(['\"])(.*?)\4|(\S+))|"
r"-filter_complex\s+(?:(['\"])(.*?)\7|(\S+))", cmd):
chain = next((g for g in m.groups() if g), "")
for part in re.split(r"[,;]", chain):
n = part.strip().split("=")[0].split("[")[0].strip()
if n and re.fullmatch(r"[a-z0-9_]+", n):
out.add(n)
return out
BUILD_LIMIT = re.compile(r"(Encoder not found|Unknown encoder|Decoder not found|Unknown decoder|"
r"Protocol not found|Demuxer not found|Filter not found|Unknown filter)", re.I)
for rid, res in results.items():
if res["label"] != "fails" or not BUILD_LIMIT.search(res["reason"]):
continue
cmd = next(r["ffmpeg_command"] for r in unique if r["id"] == rid)
missing = [f"encoder {e}" for e in re.findall(r"(?:-c:v|-c:a|-vcodec|-acodec)\s+(\S+)", cmd)
if e not in ("copy", "none") and e not in ENC_LIST]
missing += [f"filter {f}" for f in cmd_filters(cmd) if not filter_exists(f)]
if missing:
res["label"] = "static-only"
res["reason"] = "build limitation: " + "; ".join(missing)
# ---------------------------------------------------------------- write out
rows = []
for r in records:
rid = r["id"]
if rid in dup_of:
res = {"label": "dup", "reason": f"duplicate of id {dup_of[rid]}", "notes": [], "category": ""}
else:
res = results[rid]
rows.append({"id": rid, "natural_language": r["natural_language"], "ffmpeg_command": r["ffmpeg_command"],
"label": res["label"], "category": res["category"],
"dup_of": dup_of.get(rid, ""), "notes": "; ".join(res["notes"]), "reason": res["reason"]})
out_df = pd.DataFrame(rows)
out_df.to_csv(os.path.join(OUT, "audit_table.csv"), index=False)
live = [r for r in rows if r["label"] != "dup"]
counts = Counter(r["label"] for r in live)
cat_counts = Counter((r["category"], r["label"]) for r in live)
fails = [r for r in live if r["label"] == "fails"]
static_rows = [r for r in live if r["label"] == "static-only"]
suspicious_rows = [r for r in live if r["notes"]]
report = {
"source_rows": len(rows),
"exact_duplicates": len(rows) - len(unique),
"near_duplicates": near_dropped,
"unique_rows": len(unique),
"labels": dict(counts),
"by_category": {f"{c}|{l}": n for (c, l), n in sorted(cat_counts.items())},
"suspicious_but_runs": len(suspicious_rows),
"failing_examples": [
{"id": r["id"], "nl": r["natural_language"], "cmd": r["ffmpeg_command"],
"reason": r["reason"]} for r in fails[:10]],
"static_examples": [
{"id": r["id"], "cmd": r["ffmpeg_command"], "reason": r["reason"]} for r in static_rows[:5]],
"suspicious_examples": [
{"id": r["id"], "nl": r["natural_language"], "cmd": r["ffmpeg_command"], "notes": r["notes"]}
for r in suspicious_rows[:10]],
}
with open(os.path.join(OUT, "report.json"), "w") as f:
json.dump(report, f, indent=2)
print("\n=== AUDIT SUMMARY ===")
print(f"source rows: {len(rows)} | exact dups: {report['exact_duplicates']} | near dups: {near_dropped} | unique: {len(unique)}")
print("labels:", dict(counts))
print("by category:", dict(cat_counts))
print(f"suspicious-but-runs rows: {len(suspicious_rows)}")
print(f"\n--- {min(10, len(fails))} failing examples ---")
for e in report["failing_examples"]:
print(f"[{e['id']}] {e['nl'][:70]}\n cmd: {e['cmd'][:100]}\n why: {e['reason'][:160]}")
print("\nDONE")