"""Batch side-by-side inspector/editor for audio + two/three RTTM annotations. Scans an experiment directory whose sub-directories each contain items of the form .wav + .rttm + _3D.rttm [+ _GT.rttm], and serves a compare/edit page with prev/next navigation across all items. Panels: GT = _GT.rttm (parquet annotation, optional), A = .rttm (DiariZen), B = _3D.rttm (3D-Speaker). Speakers of every panel are auto-matched (by maximal overlap) against the anchor annotation (GT when present, else A) so matched speakers share a color, and a "diff" strip highlights every region where a selectable pair of annotations disagree (speech only in one, or attributed to different speakers). All annotations are editable (move/resize/reassign/split/ delete/create, undo/redo); each RTTM saves to "_new.rttm" next to the original file. Usage: python batch_double_rttm_viewer.py /workspace/comparison [--port 8766] open: http://127.0.0.1:8766 """ import argparse import io import json import mimetypes import os import re import threading import wave from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer AUDIO_EXTS = {".wav", ".flac", ".mp3", ".ogg", ".m4a", ".opus", ".aac"} def parse_rttm(path): """Return (segments, file_id, channel) from SPEAKER lines of an RTTM.""" segments = [] file_id, chan = None, None with open(path, encoding="utf-8") as f: for ln, line in enumerate(f, 1): line = line.strip() if not line or line.startswith((";", "#")): continue parts = line.split() if parts[0] != "SPEAKER": continue if len(parts) < 8: raise ValueError(f"{path}:{ln}: malformed SPEAKER line") start, dur = float(parts[3]), float(parts[4]) segments.append({"start": start, "end": start + dur, "speaker": parts[7]}) file_id = file_id or parts[1] chan = chan or parts[2] if not segments: raise ValueError(f"{path}: no SPEAKER lines found") segments.sort(key=lambda s: s["start"]) return segments, file_id, chan def load_audio(path): """Return (bytes, content-type, duration-or-None).""" with open(path, "rb") as f: data = f.read() if data[:4] == b"RIFF": with wave.open(io.BytesIO(data)) as w: return data, "audio/x-wav", w.getnframes() / w.getframerate() ctype = mimetypes.guess_type(path)[0] or "audio/mpeg" return data, ctype, None # let the browser report the duration def scan_items(root): """Collect audio + rttm items under root; _GT.rttm is optional.""" items = [] for ds in sorted(os.listdir(root)): d = os.path.join(root, ds) if not os.path.isdir(d): continue for fn in sorted(os.listdir(d)): stem, ext = os.path.splitext(fn) if ext.lower() not in AUDIO_EXTS: continue rttm_a = os.path.join(d, stem + ".rttm") rttm_b = os.path.join(d, stem + "_3D.rttm") rttm_gt = os.path.join(d, stem + "_GT.rttm") missing = [p for p in (rttm_a, rttm_b) if not os.path.isfile(p)] if missing: print(f"skip {ds}/{fn}: missing " f"{', '.join(os.path.basename(m) for m in missing)}") continue item = {"dataset": ds, "id": stem, "audio": os.path.join(d, fn), "a": rttm_a, "b": rttm_b} if os.path.isfile(rttm_gt): item["gt"] = rttm_gt items.append(item) return items class ItemStore: """Lazy per-item audio loading, caching the most recent item only.""" def __init__(self, items): self.items = items self._cache = {} self._lock = threading.Lock() def audio(self, idx): with self._lock: if idx in self._cache: return self._cache[idx] entry = load_audio(self.items[idx]["audio"]) with self._lock: self._cache.clear() self._cache[idx] = entry return entry def meta(self, idx): item = self.items[idx] _, _, duration = self.audio(idx) out = {"index": idx, "n_items": len(self.items), "dataset": item["dataset"], "id": item["id"], "audio_file": os.path.basename(item["audio"]), "files": {}} ends = [] for key in ("gt", "a", "b"): if key not in item: continue segments, _, _ = parse_rttm(item[key]) out_path = os.path.splitext(item[key])[0] + "_new.rttm" out["files"][key] = { "rttm_file": os.path.basename(item[key]), "out_file": os.path.basename(out_path), "segments": segments} ends.append(max(s["end"] for s in segments)) out["duration"] = duration if duration is not None else max(ends) return out def save(self, idx, which, segments): item = self.items[idx] if which not in item or which not in ("gt", "a", "b"): raise ValueError(f"unknown rttm key: {which!r}") src = item[which] try: _, fid, chan = parse_rttm(src) except ValueError: fid, chan = None, None fid = fid or item["id"] chan = chan or "1" out_path = os.path.splitext(src)[0] + "_new.rttm" segs = sorted(segments, key=lambda s: float(s["start"])) lines = [] for s in segs: start, end = float(s["start"]), float(s["end"]) spk = re.sub(r"\s+", "_", str(s["speaker"]).strip()) if not spk: raise ValueError("empty speaker label") if end <= start or start < 0: raise ValueError(f"invalid segment [{start}, {end}]") lines.append(f"SPEAKER {fid} {chan} {start:.3f} {end - start:.3f} " f" {spk} \n") with open(out_path, "w", encoding="utf-8") as f: f.writelines(lines) return out_path, len(lines) PAGE = """ 批量多 RTTM 对比编辑器
批量多 RTTM 对比
选区 拖动空白选择区间;单击色块选中编辑 缩放
差异对比 忽略短于 s 的差异
说话人
PgUp/PgDn=上一条/下一条 · 面板顺序 GT(parquet 标注)/A(DiariZen)/B(3D-Speaker) · 差异带在最上方,可切换对比对 · 单击色块=选中编辑 · 双击色块=播放该段 · 拖动色块=移动 · 拖边缘=调整边界 · Alt+空白拖动=新建段 · 泳道"+段"=把选区加为该说话人的段 · Del=删除 S=拆分 Ctrl+Z/Ctrl+Shift+Z=撤销/重做 · 空格=播放/暂停 ←/→=±5s Shift+←/→=±0.5s Esc=取消
""" class Handler(BaseHTTPRequestHandler): store = None def log_message(self, *args): pass def _send(self, code, body, ctype="application/json", extra=None): self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) for k, v in (extra or {}).items(): self.send_header(k, v) self.end_headers() self.wfile.write(body) def do_GET(self): try: self._route() except BrokenPipeError: pass except IndexError: self._send(404, b"item index out of range", "text/plain") except Exception as e: # surface errors to the page self._send(500, str(e).encode(), "text/plain; charset=utf-8") def do_POST(self): try: if self.path == "/api/save": length = int(self.headers.get("Content-Length", 0)) payload = json.loads(self.rfile.read(length)) path, n = self.store.save(int(payload["index"]), payload["which"], payload["segments"]) self._send(200, json.dumps({"path": path, "n": n}).encode()) else: self._send(404, b"not found", "text/plain") except BrokenPipeError: pass except Exception as e: self._send(500, str(e).encode(), "text/plain; charset=utf-8") def _route(self): if self.path in ("/", "/index.html"): self._send(200, PAGE.encode(), "text/html; charset=utf-8") elif m := re.fullmatch(r"/api/meta/(\d+)", self.path): self._send(200, json.dumps(self.store.meta(int(m.group(1)))).encode()) elif m := re.fullmatch(r"/api/audio/(\d+)", self.path): data, ctype, _ = self.store.audio(int(m.group(1))) self._serve_audio(data, ctype) else: self._send(404, b"not found", "text/plain") def _serve_audio(self, data, ctype): """Serve audio bytes with Range support so the player can seek.""" rng = self.headers.get("Range") total = len(data) if rng and (m := re.fullmatch(r"bytes=(\d*)-(\d*)", rng.strip())): start = int(m.group(1)) if m.group(1) else 0 end = int(m.group(2)) if m.group(2) else total - 1 end = min(end, total - 1) if start > end: self._send(416, b"", ctype, {"Content-Range": f"bytes */{total}"}) return chunk = data[start:end + 1] self._send(206, chunk, ctype, { "Content-Range": f"bytes {start}-{end}/{total}", "Accept-Ranges": "bytes"}) else: self._send(200, data, ctype, {"Accept-Ranges": "bytes"}) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("experiment_dir", help="directory whose sub-dirs hold .wav + .rttm " "+ _3D.rttm [+ _GT.rttm] items") ap.add_argument("--port", type=int, default=8766) ap.add_argument("--host", default="127.0.0.1") args = ap.parse_args() items = scan_items(args.experiment_dir) if not items: raise SystemExit(f"no complete items found under {args.experiment_dir}") n_gt = sum(1 for it in items if "gt" in it) Handler.store = ItemStore(items) srv = ThreadingHTTPServer((args.host, args.port), Handler) print(f"Serving {len(items)} items ({n_gt} with GT) from " f"{args.experiment_dir} at http://{args.host}:{args.port}") for i, it in enumerate(items[:10]): print(f" [{i}] {it['dataset']}/{it['id']}" f"{'' if 'gt' in it else ' (no GT)'}") if len(items) > 10: print(f" ... and {len(items) - 10} more") try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()