Spaces:
Running
Running
Download chartgen/latent_align.py from JacobLinCool/internal-model-p: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/latent_align.py
- Command line
-
hf download hf://spaces/JacobLinCool/internal-model-p/chartgen/latent_align.py
-
curl -L -o latent_align.py https://huggingface.co/spaces/JacobLinCool/internal-model-p/resolve/main/chartgen/latent_align.py
12.3 kB
| """Stage 0b of the latent design (reports/v10 設計:多層 latent.md): do two INDEPENDENT mapsets of the same song agree on | |
| where to rest (and where to roll, use big notes or triplets) as much as two mappers of the same mapset do? | |
| If they do, the agreement comes from the music (and the work belongs to the music-to-plan model). If they agree much | |
| less, it comes from coordination inside a mapset (and a mapset-level layout latent is justified). | |
| For every song with two or more mapsets (charts-only file from colab/charts_only.py, catalog for mapper ids): | |
| * cross pairs: same tier, different mapsets, no shared mapper; | |
| * within pairs: same tier, same mapset, different mappers (same songs, and all songs as a second line). | |
| Cross pairs are aligned in time: the offset is the mode of note-time differences, refined by onset F1 at +-25 ms; a | |
| pair is kept when the overlap is at least 60 s and at least 90% of B's hit notes fall within 20 ms of A's 1/48 grid. | |
| Pairs with onset F1 >= 0.9 are flagged as possible copies and reported with and without. | |
| Then, on A's real measures inside the overlap: A's labels from its own notes, B's from its notes moved into A's time. | |
| A measure is active when it has a hit note or a roll / balloon covers at least 10% of it; inside = between A's first | |
| and last active measure. Agreement: F1 of rest measures, of roll-covered measures, of big-note measures (more than | |
| half big notes), of triplet measures (at least 30% of hits on the 1/3, 1/6, 1/12 grid of A). | |
| python -m chartgen.latent_align --charts charts.pkl --out stage0b.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import pickle | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| from .dataset import GRID, _beats_at, measure_at, measure_span, roll_end_beats | |
| KINDS = ("rest", "roll", "big", "triplet") | |
| def onset_f1(a, b, tol=25.0): | |
| if len(a) == 0 or len(b) == 0: | |
| return 0.0 | |
| b = np.sort(b) | |
| j = np.clip(np.searchsorted(b, a), 1, len(b) - 1) | |
| hit = np.minimum(np.abs(a - b[j - 1]), np.abs(a - b[j])) <= tol | |
| return 2 * hit.sum() / (len(a) + len(b)) | |
| def best_offset(ta, tb, lim=3000.0): | |
| """Offset d (ms) so that tb + d lines up with ta: mode of pairwise differences, then refined twice by the median of | |
| the matched notes' residuals (an onset F1 with a 25 ms window cannot tell offsets within 25 ms apart, and a few ms | |
| already move notes to other grid positions). Returns (d, onset F1 at d).""" | |
| d = (ta[:, None] - tb[None, :]).ravel() | |
| d = d[np.abs(d) <= lim] | |
| if len(d) == 0: | |
| return 0.0, 0.0 | |
| h, e = np.histogram(d, bins=np.arange(-lim, lim + 2, 2.0)) | |
| off = float(e[np.argmax(h)] + 1.0) | |
| sa = np.sort(ta) | |
| for _ in range(2): | |
| x = tb + off | |
| j = np.clip(np.searchsorted(sa, x), 1, len(sa) - 1) | |
| nn = np.where(np.abs(sa[j - 1] - x) < np.abs(sa[j] - x), sa[j - 1], sa[j]) | |
| res = nn - x | |
| ok = np.abs(res) <= 25 | |
| if ok.sum() < 8: | |
| break | |
| off += float(np.median(res[ok])) | |
| return off, float(onset_f1(ta, tb + off)) | |
| def measure_labels(sec, t, ty, ln, lo_m, hi_m): | |
| """Per measure lo_m..hi_m-1 of the timing `sec`: active, roll-covered, big, triplet flags for notes (t ms, type, | |
| length in beats of the section where the note starts; note beats computed from t in this timing).""" | |
| n = hi_m - lo_m | |
| b = _beats_at(sec, t) | |
| hit = ty <= 3 | |
| m = measure_at(sec, np.round(b * GRID) / GRID) - lo_m | |
| st, en = measure_span(sec, np.arange(lo_m, hi_m)) | |
| L = np.maximum(en - st, 1e-6) | |
| has_hit = np.zeros(n, bool); big = np.zeros(n); nh = np.zeros(n); trip = np.zeros(n) | |
| sub = np.round(b * GRID).astype(np.int64) % GRID | |
| on_trip = (sub % 4 == 0) & (sub % 3 != 0) # on the 1/3, 1/6, 1/12 grid and not on a binary subdivision | |
| for k in range(n): | |
| mk = (m == k) & hit | |
| if mk.any(): | |
| has_hit[k] = True; nh[k] = mk.sum(); big[k] = (ty[mk] >= 2).mean(); trip[k] = on_trip[mk].mean() | |
| cover = np.zeros(n) | |
| rb = b[ty >= 4] | |
| if len(rb): | |
| for x, e in zip(rb, roll_end_beats(sec, rb, np.asarray(ln, float)[ty >= 4])): | |
| ov = np.minimum(en, e) - np.maximum(st, x) | |
| cover += np.where(ov > 0, ov, 0) / L | |
| cover[(st <= x) & (x < en)] = np.maximum(cover[(st <= x) & (x < en)], 0.11) | |
| rolled = cover >= 0.1 | |
| active = has_hit | rolled | |
| return {"active": active, "roll": rolled & ~has_hit, "big": has_hit & (big > 0.5), "triplet": has_hit & (trip >= 0.3)} | |
| def f1(x, y): | |
| tp = (x & y).sum() | |
| return 2 * tp / max(x.sum() + y.sum(), 1), int(x.sum()), int(y.sum()), int(tp) | |
| def compare(A, B, delta): | |
| """Agreement of chart B (times moved by delta into A's time) with chart A on A's measures inside the overlap.""" | |
| secA = A["sections"] | |
| ta, tb = np.asarray(A["time"], float), np.asarray(B["time"], float) + delta | |
| lo, hi = max(ta.min(), tb.min()), min(ta.max(), tb.max()) | |
| if hi - lo < 60000: | |
| return None | |
| ma = measure_at(secA, _beats_at(secA, np.array([lo, hi]))) | |
| lo_m, hi_m = int(ma[0]) + 1, int(ma[1]) # complete measures inside the overlap | |
| if hi_m - lo_m < 16: | |
| return None | |
| selA = (ta >= lo - 1) & (ta <= hi + 1); selB = (tb >= lo - 1) & (tb <= hi + 1) | |
| la = measure_labels(secA, ta[selA], np.asarray(A["type"])[selA], np.asarray(A["length_beats"])[selA], lo_m, hi_m) | |
| lb = measure_labels(secA, tb[selB], np.asarray(B["type"])[selB], np.asarray(B["length_beats"])[selB], lo_m, hi_m) | |
| act = np.where(la["active"])[0] | |
| if len(act) < 8: | |
| return None | |
| ins = np.zeros(hi_m - lo_m, bool); ins[act.min(): act.max() + 1] = True | |
| out = {"n_measures": int(ins.sum())} | |
| out["rest"] = f1(~la["active"][ins], ~lb["active"][ins]) | |
| for k in ("roll", "big", "triplet"): | |
| out[k] = f1(la[k][ins], lb[k][ins]) | |
| return out | |
| def grid_fit(A, tb): | |
| """Share of B's hit-note times within 20 ms of A's 1/48 grid.""" | |
| sec = A["sections"] | |
| b = _beats_at(sec, tb) | |
| snapped = np.round(b * GRID) / GRID | |
| j = np.clip(np.searchsorted(sec[:, 3], snapped + 1e-9, side="right") - 1, 0, len(sec) - 1) | |
| t_s = sec[j, 0] + (snapped - sec[j, 3]) * sec[j, 1] | |
| return float((np.abs(t_s - tb) <= 20).mean()) if len(tb) else 0.0 | |
| def main(argv=None): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--charts", type=Path, required=True) | |
| p.add_argument("--catalog", type=Path, default=Path("data/catalog/taiko_beatmaps.parquet")) | |
| p.add_argument("--out", type=Path, required=True) | |
| p.add_argument("--n-boot", type=int, default=1000) | |
| a = p.parse_args(argv) | |
| import pyarrow.parquet as pq | |
| from .train import song_split | |
| cat = {r["beatmap_id"]: r for r in pq.read_table(a.catalog, columns=["beatmap_id", "mapper_user_id", "approved_date"]).to_pylist()} | |
| mapper = {b: r["mapper_user_id"] for b, r in cat.items()} | |
| year = lambda b: int((cat[b]["approved_date"] or "0")[:4] or 0) # noqa: E731 | |
| songs = pickle.load(open(a.charts, "rb")) | |
| by_key = defaultdict(list) | |
| for s in songs: | |
| key = s.get("song_key") or str(s["beatmapset_id"]) | |
| if song_split(key) == "test": | |
| continue | |
| by_key[key].append(s) | |
| rows = {"cross": [], "within_same_songs": [], "within_all": []} | |
| n_cand = n_kept = n_copy = 0 | |
| for key, sets in by_key.items(): | |
| charts = [(s["beatmapset_id"], c) for s in sets for c in s["charts"] if len(c["time"]) >= 16 and mapper.get(c["beatmap_id"]) is not None] | |
| multi = len({sid for sid, _ in charts}) >= 2 | |
| for i in range(len(charts)): | |
| for j in range(len(charts)): | |
| if i == j: | |
| continue | |
| (si, A), (sj, B) = charts[i], charts[j] | |
| if int(A["tier"]) != int(B["tier"]) or mapper[A["beatmap_id"]] == mapper[B["beatmap_id"]]: | |
| continue | |
| hA, hB = np.asarray(A["type"]) <= 3, np.asarray(B["type"]) <= 3 | |
| ta, tb = np.asarray(A["time"], float)[hA], np.asarray(B["time"], float)[hB] | |
| if si == sj: | |
| r = compare(A, B, 0.0) | |
| if r is not None: | |
| r.update(song=key, copy=False, dy=abs(year(A["beatmap_id"]) - year(B["beatmap_id"]))) | |
| rows["within_all"].append(r) | |
| if multi: | |
| rows["within_same_songs"].append(r) | |
| continue | |
| n_cand += 1 | |
| d, fbest = best_offset(ta, tb) | |
| if grid_fit(A, tb + d) < 0.9: | |
| continue | |
| r = compare(A, B, d) | |
| if r is None: | |
| continue | |
| n_kept += 1 | |
| r.update(song=key, copy=fbest >= 0.9, offset=d, onset_f1=fbest, dy=abs(year(A["beatmap_id"]) - year(B["beatmap_id"]))) | |
| n_copy += r["copy"] | |
| rows["cross"].append(r) | |
| rng = np.random.default_rng(0) | |
| def summary(rs): | |
| if not rs: | |
| return None | |
| songs_ = sorted({r["song"] for r in rs}); idx = {s: [i for i, r in enumerate(rs) if r["song"] == s] for s in songs_} | |
| def pooled(ii): # pooled F1 over measures of the chosen pairs | |
| out = {} | |
| for k in KINDS: | |
| tp = sum(rs[i][k][3] for i in ii); nx = sum(rs[i][k][1] for i in ii); ny = sum(rs[i][k][2] for i in ii) | |
| out[k] = 2 * tp / max(nx + ny, 1) | |
| return out | |
| est = pooled(range(len(rs))) | |
| bs = [pooled([i for s in rng.choice(songs_, len(songs_)) for i in idx[s]]) for _ in range(a.n_boot)] | |
| return {"n_pairs": len(rs), "n_songs": len(songs_), **{k: [est[k], *np.percentile([b[k] for b in bs], [2.5, 97.5]).tolist()] for k in KINDS}} | |
| def paired(cross, within): | |
| """Songs with both kinds of pairs: pooled F1 of cross minus within, song bootstrap of the difference.""" | |
| both = sorted({r["song"] for r in cross} & {r["song"] for r in within}) | |
| if len(both) < 5: | |
| return None | |
| def pf(rs, ss): | |
| ss = set(ss); rs = [r for r in rs if r["song"] in ss] | |
| return {k: 2 * sum(r[k][3] for r in rs) / max(sum(r[k][1] + r[k][2] for r in rs), 1) for k in KINDS} | |
| est_c, est_w = pf(cross, both), pf(within, both) | |
| bs = [] | |
| for _ in range(a.n_boot): | |
| pick = list(rng.choice(both, len(both))) | |
| # duplicates count: expand the pair lists by the multiplicity of their song | |
| mult = {s_: pick.count(s_) for s_ in set(pick)} | |
| c = [r for r in cross if r["song"] in mult for _ in range(mult[r["song"]])] | |
| w = [r for r in within if r["song"] in mult for _ in range(mult[r["song"]])] | |
| fc, fw = pf(c, mult), pf(w, mult) | |
| bs.append({k: fc[k] - fw[k] for k in KINDS}) | |
| return {"n_songs": len(both), **{k: {"cross": est_c[k], "within": est_w[k], "diff": [est_c[k] - est_w[k], *np.percentile([b[k] for b in bs], [2.5, 97.5]).tolist()]} for k in KINDS}} | |
| cross_nc = [r for r in rows["cross"] if not r["copy"]] | |
| res = {"paired_same_songs": paired(cross_nc, rows["within_same_songs"]), | |
| "paired_same_songs_era2": paired([r for r in cross_nc if r["dy"] <= 2], rows["within_same_songs"]), | |
| "candidates_cross": n_cand, "kept_cross": n_kept, "possible_copies": n_copy, | |
| "cross": summary(rows["cross"]), "cross_no_copies": summary([r for r in rows["cross"] if not r["copy"]]), | |
| "within_same_songs": summary(rows["within_same_songs"]), "within_all": summary(rows["within_all"])} | |
| a.out.write_text(json.dumps(res, indent=1)) | |
| print(f"cross candidates {n_cand}, kept {n_kept}, possible copies {n_copy}") | |
| for k in ("paired_same_songs", "paired_same_songs_era2"): | |
| v = res[k] | |
| if v: | |
| print(f"{k} ({v['n_songs']} songs): " + " ".join(f"{q} cross {v[q]['cross']:.3f} within {v[q]['within']:.3f} diff {v[q]['diff'][0]:+.3f} [{v[q]['diff'][1]:+.3f},{v[q]['diff'][2]:+.3f}]" for q in KINDS)) | |
| for k in ("cross", "cross_no_copies", "within_same_songs", "within_all"): | |
| v = res[k] | |
| if v: | |
| print(f"{k:18s} pairs {v['n_pairs']:5d} songs {v['n_songs']:4d} " + " ".join(f"{q} {v[q][0]:.3f} [{v[q][1]:.3f},{v[q][2]:.3f}]" for q in KINDS)) | |
| if __name__ == "__main__": | |
| main() | |