speaker-id-noise / code /summarize_external_cleaned.py
NirbhaySinghNarang2711's picture
Add files using upload-large-folder tool
aa09fa6 verified
Raw History Blame Contribute Delete
7.52 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import csv
import hashlib
import json
from pathlib import Path
import numpy as np
from sklearn.metrics import roc_curve
EXPECTED_TRIAL_SHA256 = "0bc0a0fe3e557f1a75fb71e566d862d460709e80a4fe28e80e49bc0ab3a536ea"
SNRS = (-10, -5, 0, 5, 10, 15, 20)
CONDITIONS = ("clean",) + tuple(
f"{category}_{snr}"
for category in ("speech", "music", "noise")
for snr in SNRS
)
MODELS = (
("titanet_large", "NVIDIA TitaNet-Large"),
("campplus_lm_en_voxceleb", "WeSpeaker CAM++-LM English VoxCeleb"),
("w2v_bert2_lm", "WeSpeaker W2V-BERT 2.0-LM English VoxCeleb"),
)
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def read_index(path: Path) -> list[str]:
with path.open(newline="", encoding="utf-8") as stream:
rows = list(csv.DictReader(stream))
rows.sort(key=lambda row: int(row["embedding_index"]))
return [row["relative_path"] for row in rows]
def interpolated_eer(labels: np.ndarray, scores: np.ndarray) -> float:
fpr, tpr, _ = roc_curve(labels, scores, drop_intermediate=False)
fnr = 1.0 - tpr
delta = fpr - fnr
crossing = np.flatnonzero(delta >= 0)
if not len(crossing):
index = int(np.argmin(np.abs(delta)))
return float((fpr[index] + fnr[index]) / 2.0)
high = int(crossing[0])
if high == 0:
return float((fpr[0] + fnr[0]) / 2.0)
low = high - 1
denominator = float(delta[high] - delta[low])
weight = 0.0 if denominator == 0 else float(-delta[low] / denominator)
return float(fpr[low] + weight * (fpr[high] - fpr[low]))
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--run", type=Path, required=True)
parser.add_argument("--trials", type=Path, required=True)
args = parser.parse_args()
if sha256(args.trials) != EXPECTED_TRIAL_SHA256:
raise RuntimeError("Cleaned trial checksum mismatch")
labels_list: list[int] = []
pairs: list[tuple[str, str]] = []
for line in args.trials.read_text().splitlines():
if line.strip():
label, left, right = line.split()
labels_list.append(int(label))
pairs.append((left, right))
labels = np.asarray(labels_list, dtype=np.int8)
available_models = tuple(
item for item in MODELS if (args.run / item[0] / "report.json").exists()
)
if not available_models:
raise RuntimeError("No completed model reports found")
reference_order = read_index(
args.run / available_models[0][0] / "embedding_index.csv"
)
reference_index = {path: index for index, path in enumerate(reference_order)}
missing = sorted({path for pair in pairs for path in pair if path not in reference_index})
if missing:
raise RuntimeError(f"Missing {len(missing)} cleaned-trial references")
first = np.fromiter((reference_index[pair[0]] for pair in pairs), dtype=np.int32)
second = np.fromiter((reference_index[pair[1]] for pair in pairs), dtype=np.int32)
summary_rows: list[dict] = []
condition_rows: list[dict] = []
reports = {}
for key, display in available_models:
root = args.run / key
if read_index(root / "embedding_index.csv") != reference_order:
raise RuntimeError(f"Reference order differs: {key}")
embeddings = np.load(root / "embeddings.npy", mmap_mode="r")
if embeddings.shape[0] != len(CONDITIONS):
raise RuntimeError(f"Condition count differs: {key}")
norms = np.linalg.norm(embeddings, axis=-1)
if not bool(np.all((norms > 0.99) & (norms < 1.01))):
raise RuntimeError(f"Invalid embedding norm: {key}")
clean_scores = np.einsum(
"ij,ij->i", embeddings[0, first], embeddings[0, second]
)
scores_by_condition: dict[str, np.ndarray] = {}
for condition_index, condition in enumerate(CONDITIONS[1:], start=1):
forward = np.einsum(
"ij,ij->i", embeddings[0, first], embeddings[condition_index, second]
)
reverse = np.einsum(
"ij,ij->i", embeddings[condition_index, first], embeddings[0, second]
)
scores = (forward + reverse) / 2.0
scores_by_condition[condition] = scores
category, snr = condition.rsplit("_", 1)
condition_rows.append(
{
"model_key": key,
"model": display,
"category": "babble" if category == "speech" else category,
"snr_db": int(snr),
"eer_percent": interpolated_eer(labels, scores) * 100.0,
}
)
groups = {
"all_noisy": list(CONDITIONS[1:]),
"babble": [f"speech_{snr}" for snr in SNRS],
"music": [f"music_{snr}" for snr in SNRS],
"noise": [f"noise_{snr}" for snr in SNRS],
}
aggregates = {}
for group, selected in groups.items():
scores = np.concatenate([scores_by_condition[item] for item in selected])
aggregate_labels = np.tile(labels, len(selected))
aggregates[group] = interpolated_eer(aggregate_labels, scores) * 100.0
report = json.loads((root / "report.json").read_text())
reports[key] = {
"checkpoint_sha256": report["model"]["checkpoint_sha256"],
"metadata": report["model"]["metadata"],
}
summary_rows.append(
{
"model_key": key,
"model": display,
"clean_eer_percent": interpolated_eer(labels, clean_scores) * 100.0,
"all_noisy_eer_percent": aggregates["all_noisy"],
"babble_eer_percent": aggregates["babble"],
"music_eer_percent": aggregates["music"],
"noise_eer_percent": aggregates["noise"],
}
)
for name, rows in (
("benchmark_summary_cleaned_protocol.csv", summary_rows),
("clean_noisy_per_condition_cleaned_protocol.csv", condition_rows),
):
with (args.run / name).open("w", newline="", encoding="utf-8") as stream:
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
payload = {
"status": "PASS",
"protocol": {
"name": "VoxCeleb1-O cleaned",
"trial_file": args.trials.name,
"trial_sha256": EXPECTED_TRIAL_SHA256,
"trials": len(labels),
"positive_trials": int(labels.sum()),
"negative_trials": int(len(labels) - labels.sum()),
"unique_references": len({path for pair in pairs for path in pair}),
"noisy_scoring": "clean enrollment to noisy probe, both directions averaged",
"aggregate": "scores and labels pooled before EER calculation",
},
"models": reports,
"completed_models": len(available_models),
"expected_models": len(MODELS),
"summary": summary_rows,
}
(args.run / "benchmark_summary_cleaned_protocol.json").write_text(
json.dumps(payload, indent=2, sort_keys=True) + "\n"
)
print(json.dumps(payload, indent=2, sort_keys=True))
if __name__ == "__main__":
main()