"""Side-by-side inspector/editor for one audio file plus two RTTM annotations. Serves a localhost page with an audio player with interval-selection playback, and two stacked panels of per-speaker timeline tracks (RTTM A on top, RTTM B below) sharing one time axis. Speakers of A and B are auto-matched by maximal overlap so matched speakers share a color and vertical order, and a "diff" strip between the panels highlights every region where the two annotations disagree (speech only in A, only in B, or attributed to different speakers). Both annotations are editable in place: move/resize segments, reassign the speaker, split at the playhead, delete, create segments and speaker lanes, with undo/redo. Each RTTM saves to "_new.rttm" next to the original file. Usage: python double_rttm_viewer.py audio.wav a.rttm b.rttm [--port 8766] open: http://127.0.0.1:8766 The RTTM files are parsed for SPEAKER lines: SPEAKER ... For non-WAV audio the duration is taken from the browser's decoder, with the last RTTM segment end as the initial estimate. """ import argparse import io import json import mimetypes import os import re import wave from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer 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 PAGE = """ 双 RTTM 对比编辑器
双 RTTM 对比编辑器
选区 拖动空白选择区间;单击色块选中编辑 缩放
忽略短于 s 的差异
说话人
单击色块=选中编辑 · 双击色块=播放该段 · 拖动色块=移动 · 拖动色块边缘=调整边界 · Alt+在泳道空白拖动=新建段 · 泳道"+段"=把选区加为该说话人的段 · 空白拖动=选区 / 单击=定位 · Del=删除 S=拆分 Ctrl+Z/Ctrl+Shift+Z=撤销/重做 · 空格=播放/暂停 ←/→=±5s Shift+←/→=±0.5s Esc=取消
""" class Handler(BaseHTTPRequestHandler): audio_bytes = b"" ctype = "audio/x-wav" meta = {} files = {} # {"a"/"b": {"fid", "chan", "out_path"}} 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 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)) self._save(payload) 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 _save(self, payload): which = payload.get("which") if which not in self.files: raise ValueError(f"unknown rttm key: {which!r}") info = self.files[which] segs = sorted(payload["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 {info['fid']} {info['chan']} " f"{start:.3f} {end - start:.3f} " f" {spk} \n") with open(info["out_path"], "w", encoding="utf-8") as f: f.writelines(lines) self._send(200, json.dumps( {"path": info["out_path"], "n": len(lines)}).encode()) def _route(self): if self.path in ("/", "/index.html"): self._send(200, PAGE.encode(), "text/html; charset=utf-8") elif self.path == "/api/meta": self._send(200, json.dumps(self.meta).encode()) elif self.path == "/api/audio": self._serve_audio(self.audio_bytes, self.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("audio", help="path to the audio file (wav/mp3/...)") ap.add_argument("rttm_a", help="path to the first RTTM file (panel A)") ap.add_argument("rttm_b", help="path to the second RTTM file (panel B)") ap.add_argument("--port", type=int, default=8766) ap.add_argument("--host", default="127.0.0.1") args = ap.parse_args() data, ctype, duration = load_audio(args.audio) file_meta, files = {}, {} for key, path in (("a", args.rttm_a), ("b", args.rttm_b)): segments, fid, chan = parse_rttm(path) out_path = os.path.splitext(path)[0] + "_new.rttm" files[key] = {"fid": fid or os.path.splitext( os.path.basename(args.audio))[0], "chan": chan or "1", "out_path": out_path} file_meta[key] = {"rttm_file": os.path.basename(path), "out_file": os.path.basename(out_path), "segments": segments} if duration is None: # refined client-side once the browser decodes it duration = max(s["end"] for k in file_meta for s in file_meta[k]["segments"]) Handler.audio_bytes = data Handler.ctype = ctype Handler.files = files Handler.meta = { "audio_file": os.path.basename(args.audio), "duration": duration, "a": file_meta["a"], "b": file_meta["b"], } srv = ThreadingHTTPServer((args.host, args.port), Handler) print(f"Serving {args.audio}\n A: {args.rttm_a} " f"({len(file_meta['a']['segments'])} segments)\n B: {args.rttm_b} " f"({len(file_meta['b']['segments'])} segments)\n" f"at http://{args.host}:{args.port}\n" f"Edits save to {files['a']['out_path']} / {files['b']['out_path']}") try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()