File size: 5,997 Bytes
3463967
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#!/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()