"""Visual inspector for an audio file plus its RTTM annotation. Serves a localhost page with an audio player with interval-selection playback, plus per-speaker timeline tracks marking every annotated speech segment from the RTTM file. Usage: python rttm_viewer.py /workspace/foo.wav /workspace/foo.rttm open: http://127.0.0.1:8765 The RTTM file is 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) from the SPEAKER lines of an RTTM file.""" segments = [] file_id = 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] if not segments: raise ValueError(f"{path}: no SPEAKER lines found") segments.sort(key=lambda s: s["start"]) return segments, file_id 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 标注检查器
选区 在时间轴或轨道上拖动以选择区间;单击色块选中该段 缩放
快捷键:← / → 后退/前进 5 秒,空格 播放/暂停,Esc 清除选区;播放中手动滚动会暂时关闭"跟随播放"
""" class Handler(BaseHTTPRequestHandler): audio_bytes = b"" ctype = "audio/x-wav" meta = {} 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 _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", help="path to the RTTM annotation file") ap.add_argument("--port", type=int, default=8765) ap.add_argument("--host", default="127.0.0.1") args = ap.parse_args() segments, file_id = parse_rttm(args.rttm) data, ctype, duration = load_audio(args.audio) if duration is None: # refined client-side once the browser decodes it duration = max(s["end"] for s in segments) Handler.audio_bytes = data Handler.ctype = ctype Handler.meta = { "id": file_id, "audio_file": os.path.basename(args.audio), "rttm_file": os.path.basename(args.rttm), "duration": duration, "segments": segments, } srv = ThreadingHTTPServer((args.host, args.port), Handler) print(f"Serving {args.audio} + {args.rttm} " f"({len(segments)} segments) at http://{args.host}:{args.port}") try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()