MR-Bench-H / tools /fill_transcripts.py
Bluexxx's picture
MR-Bench-H v2.0.1
e259ac7 verified
Raw History Blame Contribute Delete
7.16 kB
#!/usr/bin/env python3
"""Restore the transcripts MR-Bench-H does not redistribute, from your own copies of the source datasets.
Writes a copy of the items file in which every "transcript": null is filled (and, for IEMOCAP, "source_label" =
(valence - 3) / 2 from EmoEvaluation). Texts are produced exactly as in the reference pipeline:
CMU-MOSI / CMU-MOSEI / CH-SIMS / CH-SIMS v2.0
--<src> label.csv or meta.csv of the raw release (columns video_id, clip_id, text), or an MMSA processed
pickle (aligned_50.pkl / unaligned_39.pkl / sims_unaligned.pkl: raw_text + id)
MUStARD++ --mustardpp mustard++_text.csv (columns KEY, SENTENCE)
MELD --meld folder with train_sent_emo.csv, dev_sent_emo.csv, test_sent_emo.csv (curly quotes -> straight)
IEMOCAP --iemocap IEMOCAP_full_release (Session*/dialog/transcriptions + EmoEvaluation; bracketed non-verbal
annotations such as [LAUGHTER] are removed, as they would leak the other channels)
python tools/fill_transcripts.py --items data/test.jsonl --out data/test.local.jsonl \
--iemocap /data/IEMOCAP_full_release --sims /data/SIMS/label.csv --simsv2 /data/chsimsv2/meta.csv \
--mustardpp /data/mustardpp/mustard++_text.csv
python tools/fill_transcripts.py --items data/test.jsonl --out /dev/null --mosi /data/MOSI/label.csv --verify
Do not redistribute the filled file: it contains text whose licence does not allow it (IEMOCAP in particular).
"""
import argparse
import csv
import glob
import json
import os
import pickle
import re
import sys
MMSA = ("mosi", "mosei", "sims", "simsv2")
def mmsa_texts(path):
"""{(split or None, id): text} from a label/meta CSV or an MMSA pickle."""
out = {}
if path.endswith(".pkl"):
with open(path, "rb") as f:
blob = pickle.load(f)
for split, d in blob.items():
if isinstance(d, dict) and "raw_text" in d and "id" in d:
for i, t in zip(d["id"], d["raw_text"]):
out[str(i)] = str(t)
return out
with open(path, encoding="utf-8") as f:
for r in csv.DictReader(f):
out[f"{r['video_id']}$_${r['clip_id']}"] = r["text"]
return out
def mustardpp_texts(path):
with open(path, encoding="utf-8", errors="replace") as f:
return {r["KEY"]: r["SENTENCE"] for r in csv.DictReader(f)}
def meld_texts(folder):
out = {}
for split in ["train", "dev", "test"]:
p = os.path.join(folder, f"{split}_sent_emo.csv")
if not os.path.exists(p):
continue
with open(p, encoding="utf-8", errors="replace") as f:
for r in csv.DictReader(f):
t = r["Utterance"].replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
out[(split, f"dia{r['Dialogue_ID']}_utt{r['Utterance_ID']}")] = t
return out
def iemocap_texts(root):
"""{utterance id: (text, source_label)}"""
hits = glob.glob(os.path.join(root, "Session1")) + glob.glob(os.path.join(root, "*", "Session1"))
if not hits:
sys.exit(f"--iemocap: no Session1 folder under {root}")
top = os.path.dirname(hits[0])
out = {}
for sess in range(1, 6):
sd = os.path.join(top, f"Session{sess}", "dialog")
trans, val = {}, {}
for f in glob.glob(os.path.join(sd, "transcriptions", "*.txt")):
for line in open(f, encoding="utf-8", errors="replace"):
m = re.match(r"(Ses\S+) \[(\d+\.\d+)-(\d+\.\d+)\]: (.*)", line.strip())
if m:
trans[m.group(1)] = re.sub(r"\s+", " ", re.sub(r"\[[A-Za-z_ ]+\]", " ", m.group(4))).strip()
for f in glob.glob(os.path.join(sd, "EmoEvaluation", "*.txt")):
for line in open(f, encoding="utf-8", errors="replace"):
m = re.match(r"\[(\d+\.\d+) - (\d+\.\d+)\]\s+(\S+)\s+(\S+)\s+\[(\d+\.\d+), (\d+\.\d+), (\d+\.\d+)\]", line.strip())
if m:
val[m.group(3)] = float(m.group(5))
for u, t in trans.items():
out[u] = (t, round((val[u] - 3.0) / 2.0, 3) if u in val else None)
return out
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--items", required=True)
ap.add_argument("--out", required=True)
for s in MMSA:
ap.add_argument(f"--{s}", default=None, help="label.csv / meta.csv or MMSA .pkl")
ap.add_argument("--mustardpp", default=None, help="mustard++_text.csv")
ap.add_argument("--meld", default=None, help="folder with *_sent_emo.csv")
ap.add_argument("--iemocap", default=None, help="IEMOCAP_full_release")
ap.add_argument("--overwrite", action="store_true", help="also replace transcripts that are already present")
ap.add_argument("--verify", action="store_true", help="compare present transcripts with your copy and report")
args = ap.parse_args()
lookup = {}
for s in MMSA:
if getattr(args, s):
t = mmsa_texts(getattr(args, s))
lookup[s] = lambda it, t=t: t.get(it["source_id"])
if args.mustardpp:
t = mustardpp_texts(args.mustardpp)
lookup["mustardpp"] = lambda it, t=t: t.get(it["source_id"])
if args.meld:
t = meld_texts(args.meld)
lookup["meld"] = lambda it, t=t: t.get((it["source_split"], it["source_id"]))
iemo = iemocap_texts(args.iemocap) if args.iemocap else None
if iemo is not None:
lookup["iemocap"] = lambda it: (iemo.get(it["source_id"]) or (None, None))[0]
stats = {}
with open(args.items, encoding="utf-8") as f, open(args.out, "w", encoding="utf-8") as g:
for line in f:
it = json.loads(line)
s = it["source"]
st = stats.setdefault(s, {"items": 0, "filled": 0, "not_found": 0, "still_missing": 0, "verified": 0, "differs": 0})
st["items"] += 1
if s in lookup:
txt = lookup[s](it)
if it.get("transcript") is not None and args.verify and txt is not None:
st["verified" if txt == it["transcript"] else "differs"] += 1
if it.get("transcript") is None or args.overwrite:
if txt is None:
st["not_found"] += 1
else:
it["transcript"], it["transcript_status"] = txt, "filled_locally"
st["filled"] += 1
if s == "iemocap" and it.get("source_label") is None:
it["source_label"] = (iemo.get(it["source_id"]) or (None, None))[1]
st["still_missing"] += it.get("transcript") is None
g.write(json.dumps(it, ensure_ascii=False) + "\n")
print("| source | items | filled | not found | still missing | verified equal | differs |\n|---|---|---|---|---|---|---|")
for s, st in stats.items():
print(f"| {s} | {st['items']} | {st['filled']} | {st['not_found']} | {st['still_missing']} | {st['verified']} | {st['differs']} |")
print(f"-> {args.out} (local use only: do not redistribute)")
if __name__ == "__main__":
main()