| """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 <file-id> <chan> <onset> <duration> <NA> <NA> <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 |
|
|
|
|
| PAGE = """<!DOCTYPE html> |
| <html lang="zh"> |
| <head> |
| <meta charset="utf-8"> |
| <title>RTTM 标注检查器</title> |
| <style> |
| :root { --bg:#14161a; --panel:#1e2128; --text:#e6e6e6; --dim:#9aa0aa; |
| --accent:#4da3ff; --sel:rgba(255,210,80,.25); --selborder:#ffd250; |
| --labelw:150px; } |
| * { box-sizing:border-box; } |
| body { margin:0; background:var(--bg); color:var(--text); |
| font:14px/1.5 system-ui,"Segoe UI",sans-serif; } |
| header { display:flex; align-items:center; gap:12px; flex-wrap:wrap; |
| padding:10px 16px; background:var(--panel); |
| border-bottom:1px solid #000; position:sticky; top:0; z-index:5; } |
| header .title { font-weight:600; } |
| header .dim { color:var(--dim); font-size:12px; } |
| button, input[type=text] { background:#2a2e37; |
| color:var(--text); border:1px solid #3a3f4a; border-radius:6px; |
| padding:4px 10px; font-size:13px; cursor:pointer; } |
| button:hover { border-color:var(--accent); } |
| button:disabled { opacity:.4; cursor:default; } |
| input[type=text] { width:110px; cursor:text; font-variant-numeric:tabular-nums; } |
| input[type=text]:focus { border-color:var(--selborder); outline:none; } |
| #controls { display:flex; align-items:center; gap:10px; flex-wrap:wrap; |
| padding:10px 16px; } |
| #audio { width:100%; } |
| .selinfo { color:var(--dim); font-size:13px; } |
| .selinfo b { color:var(--selborder); font-weight:600; } |
| #zoomwrap { margin-left:auto; display:flex; align-items:center; gap:6px; |
| color:var(--dim); font-size:12px; } |
| #tracks-outer { margin:0 16px 24px; border:1px solid #2a2e37; |
| border-radius:8px; overflow-x:auto; background:var(--panel); } |
| #tracks { position:relative; min-width:100%; } |
| #ruler { position:relative; height:26px; border-bottom:1px solid #2a2e37; |
| cursor:crosshair; user-select:none; } |
| .tick { position:absolute; top:0; height:100%; border-left:1px solid #333842; |
| color:var(--dim); font-size:10px; padding:2px 0 0 3px; } |
| .lane { position:relative; height:34px; border-bottom:1px solid #262a32; } |
| .lane-label { position:sticky; left:0; z-index:5; display:inline-flex; |
| align-items:center; gap:6px; height:100%; padding:0 8px; |
| width:var(--labelw); background:var(--panel); |
| border-right:1px solid #2a2e37; |
| font-size:12px; white-space:nowrap; |
| overflow:hidden; text-overflow:ellipsis; pointer-events:none; } |
| .gutter-mask { position:sticky; left:0; z-index:5; display:inline-block; |
| width:var(--labelw); height:100%; background:var(--panel); |
| border-right:1px solid #2a2e37; } |
| .lane-label .swatch { width:10px; height:10px; border-radius:2px; |
| flex:none; } |
| .seg { position:absolute; top:7px; height:20px; border-radius:3px; |
| opacity:.85; cursor:pointer; min-width:2px; } |
| .seg:hover { opacity:1; outline:1px solid #fff; z-index:2; } |
| #playhead { position:absolute; top:0; bottom:0; width:1px; |
| background:#ff5555; z-index:4; pointer-events:none; } |
| #selbox { position:absolute; top:0; bottom:0; background:var(--sel); |
| border-left:1px solid var(--selborder); |
| border-right:1px solid var(--selborder); |
| z-index:1; pointer-events:none; display:none; } |
| #hint { padding:0 16px 12px; color:var(--dim); font-size:12px; } |
| #err { color:#ff7070; padding:8px 16px; display:none; } |
| </style> |
| </head> |
| <body> |
| <header> |
| <span class="title">RTTM 标注检查器</span> |
| <span class="dim" id="fname"></span> |
| <span class="dim" id="rowinfo"></span> |
| </header> |
| <div id="err"></div> |
| <div id="controls"> |
| <audio id="audio" controls preload="auto"></audio> |
| </div> |
| <div id="controls"> |
| <button id="playsel" disabled>▶ 播放选区</button> |
| <label class="dim"><input type="checkbox" id="loop"> 循环</label> |
| <button id="clearsel" disabled>清除选区</button> |
| <span class="dim">选区</span> |
| <input type="text" id="selstart" placeholder="起 (秒或分:秒)"> |
| <span class="dim">→</span> |
| <input type="text" id="selend" placeholder="止 (秒或分:秒)"> |
| <button id="applysel">应用</button> |
| <span class="selinfo" id="selinfo">在时间轴或轨道上拖动以选择区间;单击色块选中该段</span> |
| <label class="dim" style="margin-left:auto"><input type="checkbox" id="follow" checked> 跟随播放</label> |
| <span id="zoomwrap" style="margin-left:0">缩放 |
| <input type="range" id="zoom" min="0" max="100" value="0" style="width:140px"> |
| <span id="zoomval">1×</span> |
| </span> |
| </div> |
| <div id="tracks-outer"><div id="tracks"> |
| <div id="ruler"></div> |
| <div id="lanes"></div> |
| <div id="selbox"></div> |
| <div id="playhead" style="left:0"></div> |
| </div></div> |
| <div id="hint">快捷键:← / → 后退/前进 5 秒,空格 播放/暂停,Esc 清除选区;播放中手动滚动会暂时关闭"跟随播放"</div> |
| <script> |
| const $ = id => document.getElementById(id); |
| const audio = $('audio'); |
| const PALETTE = ['#4da3ff','#ff9f43','#2ecc71','#e74c3c','#a55eea','#f1c40f', |
| '#1abc9c','#fd79a8','#74b9ff','#e17055','#81ecec','#b8e994', |
| '#ffbe76','#badc58','#7ed6df','#e056fd']; |
| let meta = null, dur = 0, zoomFactor = 1; |
| let sel = null; // {start, end} seconds |
| let dragging = null; |
| |
| function fmt(t) { |
| const h = Math.floor(t/3600), m = Math.floor(t%3600/60), s = t%60; |
| return (h? h+':' : '') + String(m).padStart(2,'0') + ':' + |
| s.toFixed(2).padStart(5,'0'); |
| } |
| const LABEL_W = 150; // keep in sync with --labelw |
| function pxPerSec() { |
| const w = $('tracks-outer').clientWidth - LABEL_W - 2; |
| return (w / dur) * zoomFactor; |
| } |
| // content x-position of time t (timeline starts right of the label gutter) |
| function tX(t) { return LABEL_W + t * pxPerSec(); } |
| function xToTime(clientX) { |
| const r = $('tracks').getBoundingClientRect(); |
| return Math.min(dur, Math.max(0, |
| (clientX - r.left - LABEL_W) / pxPerSec())); |
| } |
| |
| function render() { |
| const pps = pxPerSec(), width = Math.ceil(LABEL_W + dur * pps); |
| const tracks = $('tracks'); |
| tracks.style.width = width + 'px'; |
| |
| // ruler ticks: pick a "nice" step so ticks are ~90px apart |
| const ruler = $('ruler'); |
| ruler.innerHTML = ''; |
| const mask = document.createElement('div'); |
| mask.className = 'gutter-mask'; |
| ruler.appendChild(mask); |
| const steps = [0.1,0.2,0.5,1,2,5,10,15,30,60,120,300,600,1200,1800,3600]; |
| const step = steps.find(s => s*pps >= 90) || 3600; |
| for (let t = 0; t <= dur; t += step) { |
| if (tX(t) + 60 > width) break; // skip ticks whose text would overflow |
| const d = document.createElement('div'); |
| d.className = 'tick'; |
| d.style.left = tX(t) + 'px'; |
| d.textContent = fmt(t); |
| ruler.appendChild(d); |
| } |
| |
| // speaker lanes |
| const speakers = [...new Set(meta.segments.map(s => s.speaker))]; |
| const lanes = $('lanes'); |
| lanes.innerHTML = ''; |
| speakers.forEach((spk, i) => { |
| const lane = document.createElement('div'); |
| lane.className = 'lane'; |
| lane.dataset.speaker = spk; |
| const color = PALETTE[i % PALETTE.length]; |
| const label = document.createElement('span'); |
| label.className = 'lane-label'; |
| const n = meta.segments.filter(s => s.speaker === spk).length; |
| label.innerHTML = `<span class="swatch" style="background:${color}"></span>` + |
| `${spk} <span style="color:var(--dim)">(${n})</span>`; |
| lane.appendChild(label); |
| meta.segments.forEach(s => { |
| if (s.speaker !== spk) return; |
| const d = document.createElement('div'); |
| d.className = 'seg'; |
| d.style.left = tX(s.start) + 'px'; |
| d.style.width = Math.max(2, (s.end-s.start)*pps) + 'px'; |
| d.style.background = color; |
| d.title = `${spk}\\n${fmt(s.start)} → ${fmt(s.end)}` + |
| ` (${(s.end-s.start).toFixed(2)}s)`; |
| d.onclick = ev => { ev.stopPropagation(); |
| setSel(s.start, s.end); playSel(); }; |
| lane.appendChild(d); |
| }); |
| lanes.appendChild(lane); |
| }); |
| drawSel(); |
| movePlayhead(); |
| } |
| |
| function setSel(a, b, keepInputs) { |
| if (b < a) [a, b] = [b, a]; |
| sel = {start: a, end: b}; |
| $('playsel').disabled = $('clearsel').disabled = false; |
| $('selinfo').innerHTML = |
| `选区 <b>${fmt(a)}</b> → <b>${fmt(b)}</b> (${(b-a).toFixed(2)}s)`; |
| if (!keepInputs) { |
| $('selstart').value = a.toFixed(3); |
| $('selend').value = b.toFixed(3); |
| } |
| drawSel(); |
| } |
| function clearSel() { |
| sel = null; |
| $('playsel').disabled = $('clearsel').disabled = true; |
| $('selstart').value = $('selend').value = ''; |
| $('selinfo').textContent = |
| '在时间轴或轨道上拖动以选择区间;单击色块选中该段'; |
| drawSel(); |
| } |
| |
| // manual interval entry: plain seconds ("83.25") or m:s / h:m:s ("1:23.25") |
| function parseTime(str) { |
| str = str.trim(); |
| if (!str) return null; |
| const parts = str.split(':'); |
| if (parts.some(p => p.trim() === '' || isNaN(p))) return null; |
| return parts.reduce((t, p) => t * 60 + parseFloat(p), 0); |
| } |
| function applyManualSel() { |
| const a = parseTime($('selstart').value); |
| const b = parseTime($('selend').value); |
| if (a === null || b === null || a < 0 || b <= a || a >= dur) { |
| $('selinfo').innerHTML = '<span style="color:#ff7070">无效区间:' + |
| '支持 秒 或 分:秒 格式,需满足 0 ≤ 起 < 止</span>'; |
| return; |
| } |
| setSel(a, Math.min(b, dur), true); |
| playSel(); |
| } |
| function drawSel() { |
| const box = $('selbox'); |
| if (!sel) { box.style.display = 'none'; return; } |
| box.style.display = 'block'; |
| box.style.left = tX(sel.start) + 'px'; |
| box.style.width = ((sel.end-sel.start)*pxPerSec()) + 'px'; |
| } |
| function playSel() { |
| if (!sel) return; |
| audio.currentTime = sel.start; |
| audio.play(); |
| } |
| |
| // stop / loop at selection end |
| audio.addEventListener('timeupdate', () => { |
| if (sel && !audio.paused && audio.currentTime >= sel.end) { |
| if ($('loop').checked) audio.currentTime = sel.start; |
| else audio.pause(); |
| } |
| }); |
| |
| function movePlayhead() { |
| $('playhead').style.left = tX(audio.currentTime) + 'px'; |
| } |
| |
| // auto-scroll so the playhead stays visible; page-flip instead of a |
| // continuous glide so segments remain clickable while playing |
| let progScroll = false; |
| function followPlayhead(force) { |
| if (!$('follow').checked || !dur) return; |
| const outer = $('tracks-outer'); |
| if (outer.scrollWidth <= outer.clientWidth + 1) return; |
| const x = tX(audio.currentTime); |
| const lo = outer.scrollLeft + LABEL_W + 10; |
| const hi = outer.scrollLeft + outer.clientWidth - 40; |
| if (force || x < lo || x > hi) { |
| progScroll = true; |
| outer.scrollLeft = Math.max(0, |
| x - LABEL_W - (outer.clientWidth - LABEL_W) * 0.15); |
| } |
| } |
| $('tracks-outer').addEventListener('scroll', () => { |
| if (progScroll) { progScroll = false; return; } |
| if (!audio.paused) $('follow').checked = false; // manual scroll wins |
| }); |
| $('follow').onchange = () => followPlayhead(true); |
| audio.addEventListener('seeked', () => followPlayhead(true)); |
| |
| (function raf() { |
| movePlayhead(); |
| if (!audio.paused) followPlayhead(); |
| requestAnimationFrame(raf); |
| })(); |
| |
| // drag-to-select on ruler and lane background; plain click seeks |
| const tracksEl = $('tracks'); |
| tracksEl.addEventListener('mousedown', ev => { |
| if (ev.target.classList.contains('seg')) return; |
| dragging = {anchor: xToTime(ev.clientX), moved: false}; |
| ev.preventDefault(); |
| }); |
| window.addEventListener('mousemove', ev => { |
| if (!dragging) return; |
| const t = xToTime(ev.clientX); |
| if (Math.abs(t - dragging.anchor) * pxPerSec() > 3) { |
| dragging.moved = true; |
| setSel(dragging.anchor, t); |
| } |
| }); |
| window.addEventListener('mouseup', ev => { |
| if (!dragging) return; |
| if (!dragging.moved) audio.currentTime = xToTime(ev.clientX); |
| dragging = null; |
| }); |
| |
| $('zoom').oninput = () => { |
| zoomFactor = Math.pow(2, $('zoom').value / 12.5); // 1× .. 256× |
| $('zoomval').textContent = zoomFactor < 10 ? |
| zoomFactor.toFixed(1)+'×' : Math.round(zoomFactor)+'×'; |
| render(); |
| }; |
| $('playsel').onclick = playSel; |
| $('clearsel').onclick = clearSel; |
| $('applysel').onclick = applyManualSel; |
| ['selstart', 'selend'].forEach(id => $(id).addEventListener('keydown', |
| ev => { if (ev.key === 'Enter') applyManualSel(); })); |
| document.addEventListener('keydown', ev => { |
| if (ev.target.tagName === 'INPUT' && ev.target.type !== 'checkbox') return; |
| if (ev.key === 'ArrowLeft') audio.currentTime = Math.max(0, audio.currentTime - 5); |
| else if (ev.key === 'ArrowRight') audio.currentTime = Math.min(dur, audio.currentTime + 5); |
| else if (ev.key === 'Escape') clearSel(); |
| else if (ev.key === ' ') { ev.preventDefault(); |
| audio.paused ? audio.play() : audio.pause(); } |
| }); |
| window.addEventListener('resize', render); |
| |
| // non-WAV audio: the server may only estimate the duration from the last |
| // segment end, so refine it once the browser has decoded the metadata |
| audio.addEventListener('loadedmetadata', () => { |
| if (isFinite(audio.duration) && Math.abs(audio.duration - dur) > 0.05) { |
| dur = audio.duration; |
| updateInfo(); |
| render(); |
| } |
| }); |
| |
| function updateInfo() { |
| const spk = new Set(meta.segments.map(s => s.speaker)).size; |
| $('rowinfo').textContent = |
| (meta.id != null ? `id=${meta.id} · ` : '') + |
| `时长 ${fmt(dur)} · ${meta.segments.length} 段 · ${spk} 个说话人`; |
| } |
| |
| async function load() { |
| $('err').style.display = 'none'; |
| try { |
| const r = await fetch('/api/meta'); |
| if (!r.ok) throw new Error(await r.text()); |
| meta = await r.json(); |
| } catch (e) { |
| $('err').textContent = '加载失败: ' + e; |
| $('err').style.display = 'block'; |
| return; |
| } |
| dur = meta.duration; |
| clearSel(); |
| audio.src = '/api/audio'; |
| $('fname').textContent = meta.audio_file + ' + ' + meta.rttm_file; |
| document.title = 'RTTM 标注检查器 – ' + meta.audio_file; |
| updateInfo(); |
| render(); |
| } |
| |
| load(); |
| </script> |
| </body> |
| </html> |
| """ |
|
|
|
|
| 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: |
| 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: |
| 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() |
|
|