"""Visual inspector for HF diarization parquet files. Serves a localhost page that shows one parquet row at a time: an audio player with interval-selection playback, plus per-speaker timeline tracks marking every annotated speech segment. Usage: python3 parquet_viewer.py /workspace/data/parquet/data-00000.parquet open: http://127.0.0.1:8765 Expected schema: audio: struct plus segment columns, either timestamps_start/timestamps_end/speakers or seg_start/seg_end/seg_speaker. Optional columns: id (string), duration (double). """ import argparse import io import json import re import threading import wave from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import pyarrow.parquet as pq class RowStore: """Random access to parquet rows with a tiny decoded-row cache.""" SEGMENT_SCHEMAS = ( ("timestamps_start", "timestamps_end", "speakers"), ("seg_start", "seg_end", "seg_speaker"), ) def __init__(self, path): self.pf = pq.ParquetFile(path) names = set(self.pf.schema_arrow.names) for cand in self.SEGMENT_SCHEMAS: if set(cand) <= names: self.seg_cols = cand break else: raise ValueError( f"no segment columns found; expected one of " f"{self.SEGMENT_SCHEMAS}, got {sorted(names)}") self.n_rows = self.pf.metadata.num_rows self._rg_offsets = [] off = 0 for rg in range(self.pf.num_row_groups): self._rg_offsets.append(off) off += self.pf.metadata.row_group(rg).num_rows self._cache = {} self._lock = threading.Lock() def _locate(self, idx): rg = max(i for i, o in enumerate(self._rg_offsets) if o <= idx) return rg, idx - self._rg_offsets[rg] def get(self, idx): if not 0 <= idx < self.n_rows: raise IndexError(idx) with self._lock: if idx in self._cache: return self._cache[idx] rg, local = self._locate(idx) row = self.pf.read_row_group(rg).slice(local, 1).to_pylist()[0] wav = row["audio"]["bytes"] if wav[:4] == b"RIFF": with wave.open(io.BytesIO(wav)) as w: duration = w.getnframes() / w.getframerate() ctype = "audio/x-wav" else: # non-wav audio: trust the duration column, let the browser decode duration = row.get("duration") ctype = "audio/mpeg" if duration is None: raise ValueError(f"row {idx}: audio is not WAV and no " f"duration column to fall back on") c_start, c_end, c_spk = self.seg_cols segments = [ {"start": s, "end": e, "speaker": spk} for s, e, spk in zip(row[c_start], row[c_end], row[c_spk]) ] entry = { "wav": wav, "ctype": ctype, "meta": { "index": idx, "n_rows": self.n_rows, "duration": duration, "id": row.get("id"), "path": row["audio"].get("path"), "segments": segments, }, } with self._lock: self._cache.clear() # keep at most one row in memory self._cache[idx] = entry return entry PAGE = """ Parquet 标注检查器
Parquet 标注检查器
选区 在时间轴或轨道上拖动以选择区间;单击色块选中该段 缩放
快捷键:← / → 切换行,空格 播放/暂停,Esc 清除选区;播放中手动滚动会暂时关闭"跟随播放"
""" class Handler(BaseHTTPRequestHandler): store = None file_label = "" 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"row 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 _route(self): if self.path in ("/", "/index.html"): self._send(200, PAGE.encode(), "text/html; charset=utf-8") elif self.path == "/api/info": body = json.dumps({"file": self.file_label, "n_rows": self.store.n_rows}).encode() self._send(200, body) elif m := re.fullmatch(r"/api/row/(\d+)", self.path): entry = self.store.get(int(m.group(1))) self._send(200, json.dumps(entry["meta"]).encode()) elif m := re.fullmatch(r"/api/audio/(\d+)", self.path): entry = self.store.get(int(m.group(1))) self._serve_audio(entry["wav"], entry["ctype"]) else: self._send(404, b"not found", "text/plain") def _serve_audio(self, wav, ctype): """Serve audio bytes with Range support so the player can seek.""" rng = self.headers.get("Range") total = len(wav) 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 = wav[start:end + 1] self._send(206, chunk, ctype, { "Content-Range": f"bytes {start}-{end}/{total}", "Accept-Ranges": "bytes"}) else: self._send(200, wav, ctype, {"Accept-Ranges": "bytes"}) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("parquet", help="path to the parquet file") ap.add_argument("--port", type=int, default=8765) ap.add_argument("--host", default="127.0.0.1") args = ap.parse_args() Handler.store = RowStore(args.parquet) Handler.file_label = args.parquet srv = ThreadingHTTPServer((args.host, args.port), Handler) print(f"Serving {args.parquet} ({Handler.store.n_rows} rows) " f"at http://{args.host}:{args.port}") try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()