Datasets:

Modalities:
Audio
Text
ArXiv:
Libraries:
Datasets
License:
freetzan / scripts /find_duplicates.py
chrisdonahue's picture
Claude Opus 5.5
FreeTZAN: 1,200 clips (audio/<split>/<genre>/), metadata, scripts, and dataset card
9bd1d61
Raw History Blame Contribute Delete
9.18 kB
# /// script
# requires-python = ">=3.10"
# dependencies = ["pandas>=2", "numpy>=2"]
# ///
"""Find exact / near-duplicate 30 s clips involving FreeTZAN-eligible FMA-large tracks.
FMA contains re-uploads of the same recording (same artist, label/compilation re-uploads,
and the same band under a different artist id). Re-uploads under a different artist id also
break the artist-disjointness of FMA's official splits.
Candidate pairs (any of):
a) our own audio embedding (log-spectrogram band mean/std): the TOP_K nearest eligible
neighbours of each eligible track, if cosine > EMB_THRESHOLD
b) FMA's precomputed features.csv, eligible track vs. all of FMA-large, cosine > 0.9
(features.csv has ~3.8k rows that are identical across unrelated tracks, so this alone
is not reliable; it only proposes candidates)
c) identical normalized title (eligible track vs. all of FMA-large)
Every candidate pair is verified on the audio: the best mean frame-wise cosine similarity of
log-spectrograms (with each clip's long-term average spectrum removed) over all time offsets of
+-15 s (computed for all offsets at once by FFT cross-correlation). Pairs with
audio_sim >= AUDIO_DUP_THRESHOLD are duplicates.
Note: FMA-large contains clusters of byte-identical / near-identical clips filed under unrelated
artists and titles; scripts/build_freetzan.py drops such clusters entirely.
Output: resources/duplicates.csv with one row per verified duplicate pair.
Usage: uv run scripts/find_duplicates.py [--fma-dir ...] [--scores ...]
(TuneJury scores for FMA-large: https://github.com/yonghyunk1m/TuneJury)
"""
import argparse
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
import pandas as pd
sys.path.insert(0, str(Path(__file__).parent))
import build_freetzan as B # noqa: E402
AUDIO_DUP_THRESHOLD = 0.4 # bimodal: unrelated pairs <= ~0.33, re-uploads/re-masters >= ~0.45
EMB_THRESHOLD, TOP_K = 0.9, 10
FEAT_THRESHOLD = 0.9
SR, NFFT, HOP = 8000, 512, 256
MAXLAG, MIN_OVERLAP = 470, 300 # frames: +-15 s offsets, >= ~10 s overlap
T0 = time.time()
def log(msg):
print(f'[{time.time() - T0:6.0f}s] {msg}', flush=True)
def spectrogram(path):
p = subprocess.run(['ffmpeg', '-nostdin', '-v', 'quiet', '-i', str(path), '-ac', '1', '-ar', str(SR),
'-f', 's16le', '-'], capture_output=True)
x = np.frombuffer(p.stdout, np.int16).astype(np.float32)
if len(x) < SR * 5:
return None
fr = np.lib.stride_tricks.sliding_window_view(x, NFFT)[::HOP] * np.hanning(NFFT).astype(np.float32)
return np.log1p(np.abs(np.fft.rfft(fr, axis=1))).astype(np.float32)
def embedding(S):
bands = S[:, 1:257].reshape(len(S), 64, 4).mean(2)
return np.concatenate([bands.mean(0), bands.std(0)])
def normalize_frames(S):
"""Remove the clip's long-term average spectrum (timbre / recording chain), then mean-centre and
unit-normalize each frame. Without the first step, unrelated recordings with a similar static
spectrum (solo piano, drones, lo-fi tape hiss) score as high as true duplicates."""
S = S - S.mean(0, keepdims=True)
S = S - S.mean(1, keepdims=True)
return (S / (np.linalg.norm(S, axis=1, keepdims=True) + 1e-6)).astype(np.float32)
def aligned_similarity(A, Bm, maxlag=MAXLAG, min_overlap=MIN_OVERLAP):
"""max over lags of mean_t <A[t+lag], Bm[t]> over the overlapping frames (rows unit-norm)."""
ta, tb = len(A), len(Bm)
n = 1 << int(np.ceil(np.log2(ta + tb)))
c = np.fft.irfft((np.fft.rfft(A, n, axis=0) * np.fft.rfft(Bm, n, axis=0).conj()).sum(1), n)
lags = np.arange(-maxlag, maxlag + 1)
overlap = np.where(lags >= 0, np.minimum(ta - lags, tb), np.minimum(ta, tb + lags))
ok = overlap >= min_overlap
if not ok.any():
return np.nan
return float((c[lags[ok] % n] / overlap[ok]).max())
def topk_neighbors(Q, X, qids, xids, thr, k=None, chunk=2000):
out = []
for s in range(0, len(Q), chunk):
S = Q[s:s + chunk] @ X.T
if k is not None:
kk = min(k + 1, S.shape[1])
idx = np.argpartition(-S, kk - 1, axis=1)[:, :kk]
val = np.take_along_axis(S, idx, 1)
r, j = np.nonzero(val > thr)
c = idx[r, j]
else:
r, c = np.nonzero(S > thr)
out += [(qids[s + a], xids[b]) for a, b in zip(r, c) if qids[s + a] != xids[b]]
return out
def zscore_unit(X):
X = (X - X.mean(0)) / (X.std(0) + 1e-6)
return X / np.linalg.norm(X, axis=1, keepdims=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--fma-dir', required=True, help='FMA root with fma_large/ and fma_metadata/')
ap.add_argument('--scores', default='resources/fma_large_scores_rescored.csv')
ap.add_argument('--out', default='resources/duplicates.csv')
ap.add_argument('--workers', type=int, default=48)
args = ap.parse_args()
t, g = B.load(args.fma_dir, args.scores)
thr = t.reward_score.median()
t['license_family'] = t.track_license.map(B.license_family)
sets, anc = B.build_class_sets(g)
t['genre'] = t.track_genres.map(lambda L: B.assign_label(L, sets, anc))
elig = t[(t.reward_score >= thr) & t.license_family.notna()
& (t.track_duration >= B.MIN_DURATION_S) & t.genre.notna()]
eids = elig.index.values
eset = set(eids)
log(f'eligible tracks: {len(eids)}')
meta = Path(args.fma_dir) / 'fma_metadata'
allt = pd.read_csv(meta / 'tracks.csv', index_col=0, header=[0, 1], low_memory=False)
allt.columns = ['_'.join(c) for c in allt.columns]
allt = allt[allt.set_subset.isin(['small', 'medium', 'large'])]
# decode every eligible clip once; keep normalized frames for verification
frames, embs = {}, {}
def decode(tid):
S = spectrogram(B.mp3_path(args.fma_dir, tid))
if S is not None:
embs[tid] = embedding(S)
frames[tid] = normalize_frames(S)
with ThreadPoolExecutor(args.workers) as ex:
list(ex.map(decode, eids))
ok = np.array([x in embs for x in eids])
log(f'decoded {ok.sum()} / {len(eids)} eligible clips')
# a) own embeddings, eligible vs eligible, top-k
E = zscore_unit(np.stack([embs[x] for x in eids[ok]]).astype(np.float32))
cand = set(tuple(sorted(p)) for p in topk_neighbors(E, E, eids[ok], eids[ok], EMB_THRESHOLD, TOP_K))
log(f'(a) own-embedding candidates (top-{TOP_K}, cos > {EMB_THRESHOLD}): {len(cand)}')
# b) FMA features, eligible vs all FMA-large
f = pd.read_csv(meta / 'features.csv', index_col=0, header=[0, 1, 2])
f = f.loc[f.index.intersection(allt.index)]
F = zscore_unit(f.values.astype(np.float32))
pos = {x: i for i, x in enumerate(f.index)}
qi = np.array([pos[x] for x in eids if x in pos])
nb = topk_neighbors(F[qi], F, f.index.values[qi], f.index.values, FEAT_THRESHOLD)
n0 = len(cand)
cand |= set(tuple(sorted(p)) for p in nb)
log(f'(b) FMA-feature candidates added: {len(cand) - n0}')
# c) same normalized title, eligible vs all FMA-large (skip generic titles)
allt['_title'] = allt.track_title.map(B.norm_title)
groups = allt[allt._title.str.len() >= 4].groupby('_title').groups
n0 = len(cand)
for idx in groups.values():
if len(idx) < 2 or len(idx) > 25:
continue
idx = list(idx)
for i, a in enumerate(idx):
for b in idx[i + 1:]:
if a in eset or b in eset:
cand.add(tuple(sorted((a, b))))
log(f'(c) same-title candidates added: {len(cand) - n0}; total candidates: {len(cand)}')
# decode the non-eligible tracks that appear in candidate pairs
extra = sorted({x for p in cand for x in p} - eset)
with ThreadPoolExecutor(args.workers) as ex:
list(ex.map(decode, extra))
log(f'decoded {len(extra)} additional non-eligible clips')
# verify
def verify(pair):
A, Bm = frames.get(pair[0]), frames.get(pair[1])
return np.nan if A is None or Bm is None else aligned_similarity(A, Bm)
cand = sorted(cand)
with ThreadPoolExecutor(args.workers) as ex:
sims = list(ex.map(verify, cand, chunksize=256))
log(f'verified {len(cand)} candidate pairs')
P = pd.DataFrame(cand, columns=['track_id_a', 'track_id_b'])
P['audio_sim'] = np.round(sims, 4)
P = P[P.audio_sim >= AUDIO_DUP_THRESHOLD].copy()
for s in 'ab':
ids = P[f'track_id_{s}']
P[f'artist_id_{s}'] = allt.loc[ids, 'artist_id'].values
P[f'artist_name_{s}'] = allt.loc[ids, 'artist_name'].values
P[f'title_{s}'] = allt.loc[ids, 'track_title'].values
P[f'fma_split_{s}'] = allt.loc[ids, 'set_split'].values
P[f'eligible_{s}'] = ids.isin(eset).values
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
P.to_csv(args.out, index=False)
log(f'verified duplicate pairs (audio_sim >= {AUDIO_DUP_THRESHOLD}): {len(P)} -> {args.out}')
log(f' cross-artist: {(P.artist_id_a != P.artist_id_b).sum()} | '
f'cross-FMA-split: {(P.fma_split_a != P.fma_split_b).sum()}')
if __name__ == '__main__':
main()