cucl2's picture
Add files using upload-large-folder tool
3463967 verified
Raw History Blame Contribute Delete
6 kB
#!/usr/bin/env python3
"""
server.py — AnyAudio-Judge-Corpus-opus 数据浏览 / 质检网页(纯标准库)。
用法(在数据集根目录下): python3 viewer/server.py [--port 8080] [--readonly]
样本默认读 viewer/viewer.json,音频按相对路径从数据集根目录读取(speech / mix 音频未发布)。
不加 --readonly 时可在网页上标注,结果写到 viewer/viewer.annotations.json。
"""
import argparse
import json
import mimetypes
import os
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
HERE = Path(__file__).resolve().parent
INDEX_FILE = HERE / "index.html"
DATA_ROOT = HERE.parent
READONLY = False
ANNOT_FILE = None
SAMPLES, ANNOTS = [], {}
LOCK = threading.Lock()
def save_annots():
tmp = ANNOT_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(ANNOTS, ensure_ascii=False, indent=1), encoding="utf-8")
os.replace(tmp, ANNOT_FILE)
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def send_json(self, obj, code=200):
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urlparse(self.path)
if url.path in ("/", "/index.html"):
body = INDEX_FILE.read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif url.path == "/api/samples":
self.send_json({"samples": SAMPLES, "annotations": ANNOTS, "readonly": READONLY})
elif url.path == "/api/export":
with LOCK:
out = [dict(s, annotation=ANNOTS[str(s["id"])]) for s in SAMPLES if str(s["id"]) in ANNOTS]
self.send_json(out)
elif url.path == "/audio":
self.send_audio(parse_qs(url.query).get("id", [""])[0])
else:
self.send_error(404)
def do_POST(self):
if urlparse(self.path).path != "/api/annotate" or READONLY:
return self.send_error(404)
data = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
sid = str(data.get("id"))
if not sid.isdigit() or int(sid) >= len(SAMPLES):
return self.send_json({"error": "bad id"}, 400)
with LOCK:
ann = data.get("annotation")
if ann:
ANNOTS[sid] = ann
else:
ANNOTS.pop(sid, None)
save_annots()
self.send_json({"ok": True})
def send_audio(self, sid):
# 只允许按样本 id 取音频,不接受任意路径
if not sid.isdigit() or int(sid) >= len(SAMPLES):
return self.send_error(404)
if not SAMPLES[int(sid)]["audio"]:
return self.send_error(404, "audio not released")
path = str(DATA_ROOT / SAMPLES[int(sid)]["audio"])
try:
size = os.path.getsize(path)
except OSError:
return self.send_error(404, "audio not found")
start, end = 0, size - 1
rng = self.headers.get("Range")
if rng and rng.startswith("bytes="):
a, _, b = rng[6:].split(",")[0].partition("-")
if a:
start = int(a)
end = int(b) if b else end
elif b:
start = max(0, size - int(b))
end = min(end, size - 1)
if start > end:
self.send_response(416)
self.send_header("Content-Range", "bytes */%d" % size)
self.end_headers()
return
self.send_response(206)
self.send_header("Content-Range", "bytes %d-%d/%d" % (start, end, size))
else:
self.send_response(200)
self.send_header("Content-Type", mimetypes.guess_type(path)[0] or "audio/wav")
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(end - start + 1))
self.end_headers()
try:
with open(path, "rb") as f:
f.seek(start)
left = end - start + 1
while left > 0:
chunk = f.read(min(1 << 20, left))
if not chunk:
break
self.wfile.write(chunk)
left -= len(chunk)
except (BrokenPipeError, ConnectionResetError):
pass
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8080)
ap.add_argument("--host", default="0.0.0.0")
ap.add_argument("--sample", default=str(HERE / "viewer.json"))
ap.add_argument("--readonly", action="store_true", help="只读模式(不能标注),用于公开部署")
ap.add_argument("--annot", default=None, help="默认与 --sample 同目录、同名加 .annotations.json")
args = ap.parse_args()
global ANNOT_FILE, SAMPLES, ANNOTS, READONLY
READONLY = args.readonly
sample = Path(args.sample).resolve()
if args.annot:
ANNOT_FILE = Path(args.annot).resolve()
else:
ANNOT_FILE = sample.with_name(sample.stem + ".annotations.json")
SAMPLES = json.loads(sample.read_text(encoding="utf-8"))
ANNOTS = json.loads(ANNOT_FILE.read_text(encoding="utf-8")) if ANNOT_FILE.exists() else {}
print("samples: %s\nannotations: %s" % (sample, ANNOT_FILE), flush=True)
print("serving %d samples on http://%s:%d" % (len(SAMPLES), args.host, args.port), flush=True)
ThreadingHTTPServer((args.host, args.port), Handler).serve_forever()
if __name__ == "__main__":
main()