Datasets:
File size: 9,225 Bytes
96b3ae3 | 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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | #!/usr/bin/env python3
"""Step 2: clean, fix, and split the audited dataset.
Input : /work/out/audit_table.csv (produced by audit.py)
Output: /work/out/clean_dataset.csv - all 1,024 unique rows with labels + splits
/work/out/report_splits.json - split stats, seen/unseen families, edit log
Policy (user-approved):
- drop exact and near duplicates (label 'dup')
- exclude 'fails' rows from training/evaluation (split left empty)
- one-token fixes, logged: merge duplicate -af flags (rows 127, 231)
- 80/10/10 train/val/test grouped by main filter/codec family
- rare families (<=2 rows) go entirely to test/val so the test set contains
families absent from train; reported separately as 'unseen'
- robustness slice: test prompts rewritten with different filenames (applied
consistently to prompt AND command) and rule-based rephrasing. Never applied
to train/val. Split tag 'test-robust'.
"""
import json
import random
import re
import shlex
from collections import Counter, defaultdict
import pandas as pd
OUT = "/work/out"
SEED = 42
rng = random.Random(SEED)
df = pd.read_csv(f"{OUT}/audit_table.csv")
df = df[df.label != "dup"].copy() # 1,024 unique rows
edits = []
# ---------------------------------------------------------------- fixes
AF_FIXES = {
127: ("-af atempo=0.8 -af aresample=44100", "-af atempo=0.8,aresample=44100"),
231: ("-af atempo=0.5 -af aresample=44100", "-af atempo=0.5,aresample=44100"),
}
for rid, (old, new) in AF_FIXES.items():
m = df.id == rid
if m.any() and old in df.loc[m, "ffmpeg_command"].iloc[0]:
df.loc[m, "ffmpeg_command"] = df.loc[m, "ffmpeg_command"].str.replace(old, new, regex=False)
edits.append({"id": int(rid), "change": f"{old!r} -> {new!r}",
"reason": "second -af overrode the first; merged into one chain"})
# ---------------------------------------------------------------- families
LAVFI = {"testsrc", "testsrc2", "sine", "color", "anullsrc", "mandelbrot", "smptebars",
"smptehdbars", "rgbtestsrc", "nullsrc", "gradients", "aevalsrc", "life", "cellauto"}
def family(cmd):
if "-f concat" in cmd:
return "concat"
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) and n not in LAVFI:
return n
enc = re.findall(r"-c:v\s+(\S+)|-c:a\s+(\S+)|-vcodec\s+(\S+)|-acodec\s+(\S+)", cmd)
for tup in enc:
v = next(x for x in tup if x)
if v != "copy":
return f"codec:{v}"
if any(t.split("=")[0].split(":")[0] in LAVFI for t in shlex.split(cmd)):
return "lavfi-source"
return "plain-conversion"
df["filter_family"] = df.ffmpeg_command.map(family)
# ---------------------------------------------------------------- splits
splittable = df[df.label.isin(["runs", "static-only"])].index.tolist()
by_fam = defaultdict(list)
for i in splittable:
by_fam[df.at[i, "filter_family"]].append(i)
df["split"] = ""
unseen_fams = []
for fam, idxs in sorted(by_fam.items(), key=lambda kv: -len(kv[1])):
n = len(idxs)
if n >= 10:
rng.shuffle(idxs)
n_tr = int(round(0.8 * n))
n_va = max(1, int(round(0.1 * n)))
for i in idxs[:n_tr]:
df.at[i, "split"] = "train"
for i in idxs[n_tr:n_tr + n_va]:
df.at[i, "split"] = "val"
for i in idxs[n_tr + n_va:]:
df.at[i, "split"] = "test"
elif n in (3, 4):
# tiny family: keep one example in train, rest to val/test
rng.shuffle(idxs)
df.at[idxs[0], "split"] = "train"
df.at[idxs[1], "split"] = "val" if n == 4 else "test"
if n == 4:
df.at[idxs[2], "split"] = "test"
unseen_fams.append(fam)
else: # n <= 2: a deliberate subset goes to test, absent from train;
# the rest stay in train so the long tail does not hollow it out
if rng.random() < 0.35:
for i in idxs:
df.at[i, "split"] = "test"
unseen_fams.append(fam)
else:
for i in idxs:
df.at[i, "split"] = "train"
# ---------------------------------------------------------------- robustness
FNAME_MAP = {
"video.mp4": "input_video.mp4", "movie.mp4": "film.mp4", "clip.mp4": "segment.mp4",
"audio.wav": "sound.wav", "song.wav": "track.wav", "voice.wav": "speech.wav",
"song.mp3": "track.mp3", "audio.mp3": "sound.mp3", "music.mp3": "audio_track.mp3",
"output.mp4": "result.mp4", "output.gif": "result.gif", "output.mp3": "result.mp3",
"output.wav": "result.wav", "output.avi": "result.avi", "output.mkv": "result.mkv",
"output.webm": "result.webm", "output.mov": "result.mov", "output.m4a": "result.m4a",
"output.jpg": "result.jpg", "output.png": "result.png", "output.flac": "result.flac",
"output.aac": "result.aac", "output.ogg": "result.ogg", "thumbnail.jpg": "poster.jpg",
"frame.jpg": "snapshot.jpg", "cover.jpg": "album_art.jpg", "image.jpg": "picture.jpg",
"image.png": "picture.png", "input.jpg": "source_image.jpg", "input.png": "source_image.png",
"input.mp4": "source_video.mp4", "logo.png": "branding.png", "watermark.png": "overlay_wm.png",
"subtitles.srt": "captions.srt", "video.gif": "animation.gif", "screenshot.png": "grab.png",
"slowmotion.mp4": "slowed.mp4", "reversed.mp4": "backwards.mp4", "cropped.mp4": "cut_video.mp4",
"resized.mp4": "scaled_video.mp4", "thumbnail.png": "poster.png", "highlight.mp4": "best_of.mp4",
"cat.png": "pet.png", "kick.wav": "drum.wav", "merged.mp4": "combined_video.mp4",
"video_with_alpha.mov": "alpha_source.mov", "rgba.mov": "alpha_source2.mov",
}
REPHRASE = [
(r"\bconvert (.+?) to ", r"change \1 into "),
(r"\bresize (.+?) to ", r"scale \1 to "),
(r"\bextract (.+?) from ", r"pull \1 out of "),
(r"\badd (.+?) to ", r"apply \1 onto "),
(r"\bcreate (.+?) from ", r"make \1 out of "),
(r"\bcreate (.+?) for ", r"make \1 for "),
(r"\bremove (.+?) from ", r"delete \1 from "),
(r"\btrim ", "cut "),
(r"\bmerge ", "join "),
(r"\bslow down ", "reduce the speed of "),
(r"\bspeed up ", "increase the speed of "),
(r"\brotate ", "turn "),
(r"\bflip ", "invert "),
(r"\bcrop ", "cut out a region from "),
(r"\bincrease ", "raise "),
(r"\bdecrease ", "lower "),
(r"\bcompress ", "shrink "),
(r"\breverse ", "play backwards "),
]
def robust_variant(row):
"""Return (prompt, command, notes) or None if nothing applies."""
prompt, cmd = row.natural_language, row.ffmpeg_command
notes = []
# filename swaps, consistently in prompt and command
for old, new in FNAME_MAP.items():
if old in cmd:
cmd = cmd.replace(old, new)
if old in prompt:
prompt = prompt.replace(old, new)
notes.append(f"file {old}->{new}")
# rephrase: apply the first matching rule
for pat, rep in REPHRASE:
if re.search(pat, prompt):
prompt = re.sub(pat, rep, prompt, count=1)
notes.append(f"rephrase {pat}")
break
if not notes:
return None
return prompt, cmd, "; ".join(notes)
robust_rows = []
for _, r in df[df.split == "test"].iterrows():
v = robust_variant(r)
if v is None:
continue
p, c, notes = v
if p == r.natural_language and c == r.ffmpeg_command:
continue
robust_rows.append({
"id": f"robust-{r.id}", "natural_language": p, "ffmpeg_command": c,
"label": r.label, "category": r.category, "filter_family": r.filter_family,
"split": "test-robust", "robustness_notes": notes, "source_id": int(r.id),
})
rob = pd.DataFrame(robust_rows)
for col in ("dup_of", "notes", "reason"):
if col not in rob.columns:
rob[col] = ""
df["robustness_notes"] = ""
df["source_id"] = ""
clean = pd.concat([df, rob], ignore_index=True)
clean.to_csv(f"{OUT}/clean_dataset.csv", index=False)
# ---------------------------------------------------------------- report
core = clean[clean.split.isin(["train", "val", "test"])]
rep = {
"unique_rows": len(df),
"excluded_fails": int((df.label == "fails").sum()),
"edits": edits,
"split_counts": core.split.value_counts().to_dict(),
"split_by_label": {f"{s}|{l}": n for (s, l), n in core.groupby(["split", "label"]).size().items()},
"families_total": len(by_fam),
"unseen_families_in_test": sorted(unseen_fams),
"unseen_family_rows": int((core.split == "test").sum() and sum(
len(by_fam[f]) for f in unseen_fams)),
"robustness_rows": len(rob),
"train_families": sorted(set(df[df.split == "train"].filter_family)),
}
with open(f"{OUT}/report_splits.json", "w") as f:
json.dump(rep, f, indent=2)
print(json.dumps({k: v for k, v in rep.items() if k != "train_families"}, indent=1))
print(f"train families ({len(rep['train_families'])}):", ", ".join(rep["train_families"][:25]), "...")
print("DONE")
|