fairtalking-second-work / scripts /prepare_hdtf_splits.py
huahua123313's picture
Add files using upload-large-folder tool
7c2871f verified
Raw
History Blame Contribute Delete
5.8 kB
#!/usr/bin/env python3
"""Build HDTF id-paired subset csvs for Protocol 4.
Logic (from user's paper):
* The FairTalking-Bench Real pool is drawn from CelebV-HQ + DFDC + HDTF.
* HDTF videos that ended up in the main train.csv -> Subset A (training IDs)
* HDTF videos that ended up in the main test.csv -> Subset B (testing IDs)
* HDTF IDs that were NEVER included in FairTalking -> Subset C (unseen IDs)
(also includes HDTF videos that went into val.csv — anything not in train)
For every Real HDTF video with basename_num XXXX we check that
<root>/<gen>/XXXX_Fake_<gen>.mp4
exists for all 8 generators; rows where any generator is missing are skipped.
For Subset C we need an external list of HDTF identities not in the csv.
If --external_hdtf_ids <txt> is given, those IDs are treated as subset C.
Otherwise subset C is left empty and you fill it in later.
Output csvs have columns:
identity_id, basename_num, subset, source
and are written to $DATA_ROOT/hdtf_subset_{a,b,c}.csv.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
import pandas as pd
GENERATORS = (
"AniPortrait", "Ditto", "EDTalk", "Float",
"Hallo", "Joyvasa", "SadTalk", "Sonic",
)
def load_split(root: Path, csv_name: str) -> pd.DataFrame:
df = pd.read_csv(root / csv_name)
df["_num"] = df["basename"].str.extract(r"^(\d+)_")[0]
df["_kind"] = df["basename"].str.extract(r"_(Real|Fake)$")[0]
return df
def hdtf_real_rows(df: pd.DataFrame) -> pd.DataFrame:
# real rows from HDTF — identified by source column when present, else heuristic
real = df[df["_kind"] == "Real"].copy()
if "source" in real.columns:
# the paper's real pool column may say "real"; actual dataset tag is
# typically in filename suffix — try that as secondary check
pass
return real # caller filters further
def fakes_exist(root: Path, num: str) -> bool:
for g in GENERATORS:
if not (root / g / f"{num}_Fake_{g}.mp4").exists():
return False
return True
def find_hdtf(real_df: pd.DataFrame, root: Path) -> pd.DataFrame:
"""Look at physical Real/ dir to find which rows have *_Real_HDTF*.mp4 suffix."""
hdtf_nums = set()
for p in (root / "Real").glob("*_Real_HDTF*.mp4"):
num = p.name.split("_", 1)[0]
hdtf_nums.add(num)
sel = real_df[real_df["_num"].isin(hdtf_nums)].copy()
sel["identity_id"] = sel["basename_old"].astype(str)
sel["basename_num"] = sel["_num"]
return sel
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--data_root", required=True)
ap.add_argument(
"--external_hdtf_ids",
default=None,
help="txt file, one HDTF identity per line, that were never included in FairTalking — used for Subset C",
)
ap.add_argument("--external_hdtf_root", default=None,
help="if given, also verify Subset C videos exist under this path")
args = ap.parse_args()
root = Path(args.data_root)
train_df = load_split(root, "train.csv")
val_df = load_split(root, "val.csv")
test_df = load_split(root, "test.csv")
hdtf_train = find_hdtf(train_df, root)
hdtf_val = find_hdtf(val_df, root)
hdtf_test = find_hdtf(test_df, root)
# keep only ones that have all 8 generator fakes alongside
def _keep_with_fakes(df: pd.DataFrame) -> pd.DataFrame:
mask = df["basename_num"].apply(lambda n: fakes_exist(root, n))
return df[mask].copy()
subset_a = _keep_with_fakes(hdtf_train)
subset_b = _keep_with_fakes(hdtf_test)
# val rows merged into B (for 'seen' identity set) OR could go their own csv;
# paper uses A/B/C only, so we leave val as C candidates.
subset_a["subset"] = "A"
subset_b["subset"] = "B"
keep_cols = ["identity_id", "basename_num", "subset", "source"]
for c in keep_cols:
if c not in subset_a.columns: subset_a[c] = ""
if c not in subset_b.columns: subset_b[c] = ""
subset_a[keep_cols].to_csv(root / "hdtf_subset_a.csv", index=False)
subset_b[keep_cols].to_csv(root / "hdtf_subset_b.csv", index=False)
print(f"[prepare_hdtf_splits] A (train-seen HDTF): {len(subset_a)}")
print(f"[prepare_hdtf_splits] B (test-seen HDTF): {len(subset_b)}")
# Subset C: truly unseen HDTF identities.
# If user provides a list file, build Subset C; otherwise emit an empty csv.
subset_c = pd.DataFrame(columns=keep_cols)
if args.external_hdtf_ids and Path(args.external_hdtf_ids).exists():
ids = [ln.strip() for ln in open(args.external_hdtf_ids) if ln.strip()]
rows = []
# external HDTF videos don't have fakes in FairTalking-Bench;
# for Subset C eval we generally use only the RIGHT side (real videos)
# for identity-feature extraction. Fake side comes from inference, not from disk.
for i, ident in enumerate(ids):
rows.append({
"identity_id": ident,
"basename_num": f"EXT{i:04d}",
"subset": "C",
"source": "external_hdtf",
})
subset_c = pd.DataFrame(rows, columns=keep_cols)
subset_c.to_csv(root / "hdtf_subset_c.csv", index=False)
print(f"[prepare_hdtf_splits] C (unseen HDTF): {len(subset_c)}")
# tiny manifest for debugging
manifest = {
"train_total": len(train_df),
"val_total": len(val_df),
"test_total": len(test_df),
"hdtf_train": len(hdtf_train),
"hdtf_val": len(hdtf_val),
"hdtf_test": len(hdtf_test),
"subset_a": len(subset_a),
"subset_b": len(subset_b),
"subset_c": len(subset_c),
}
print(f"[prepare_hdtf_splits] manifest: {manifest}")
if __name__ == "__main__":
main()