File size: 21,600 Bytes
38f2c13
 
 
 
 
 
 
 
 
 
 
 
e196096
38f2c13
 
 
 
 
 
 
e196096
 
 
38f2c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e196096
 
 
 
38f2c13
 
 
 
e196096
38f2c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e196096
38f2c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env python3
"""Small local DDJ best-result annotator. Python standard library only."""
import argparse
import base64
import binascii
import struct
import zlib
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import mimetypes
import os
import sys
from pathlib import Path
import re
import tempfile
import threading
from urllib.parse import parse_qs, quote, unquote, urlsplit

APP_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(APP_DIR.parent))
from dataset_layout import model_directory

STATIC_DIR = APP_DIR / 'static'
SOURCE_RE = re.compile(r'^(?P<id>.+)_source(?P<error>_err)?\.(png|jpe?g|webp)$', re.I)
RESULT_RE = re.compile(r'^(?P<id>.+?)_result(?:_(?P<version>.+))?\.(png|jpe?g|webp)$', re.I)
EDITED_RE = re.compile(r'^(?P<id>.+)_edited(?P<error>_err)?\.(png|jpe?g|webp)$', re.I)
IMAGE_SUFFIXES = {'.png', '.jpg', '.jpeg', '.webp'}
REJECTION_REASONS = {'result_unsatisfied', 'edited_unsatisfied'}


class ReviewError(Exception):
    def __init__(self, message, status=400):
        super().__init__(message)
        self.status = status


def natural_key(value):
    return tuple((0, int(x)) if x.isdigit() else (1, x.lower())
                 for x in re.split(r'(\d+)', value))


class Dataset:
    def __init__(self, root):
        self.root = Path(root).resolve()
        if not self.root.is_dir():
            raise ValueError('数据集目录不存在')
        self.lock = threading.RLock()
        self.records = {}
        self.assets = set()
        self.scan()

    def _inside_file(self, path):
        return path.is_file() and not path.is_symlink() and path.resolve().is_relative_to(self.root)

    def scan(self):
        with self.lock:
            records, assets = {}, set()
            def fail(error):
                raise error
            for directory, folders, files in os.walk(self.root, followlinks=False, onerror=fail):
                parent = Path(directory)
                folders[:] = sorted(x for x in folders
                    if x not in {'.git', '.cache', '__pycache__'} and (parent / x).resolve() != APP_DIR)
                sources, result_groups, edited_groups = {}, {}, {}
                for name in sorted(files):
                    path = parent / name
                    if path.suffix.lower() not in IMAGE_SUFFIXES or not self._inside_file(path):
                        continue
                    match = SOURCE_RE.fullmatch(name)
                    if match:
                        identity = match['id']
                        previous = sources.get(identity)
                        if previous is None or (previous[1] and not match['error']):
                            sources[identity] = (name, bool(match['error']))
                    result = RESULT_RE.fullmatch(name)
                    if result:
                        result_groups.setdefault(result['id'], []).append(
                            {'name': name, 'version': result['version'] or 'original', 'path': path})
                    edited_match = EDITED_RE.fullmatch(name)
                    if edited_match and (edited_match['id'] not in edited_groups or not edited_match['error']):
                        edited_groups[edited_match['id']] = path
                for identity, (source, error) in sources.items():
                    folder = str(parent.relative_to(self.root))
                    model_dir = model_directory(parent, identity)
                    model = str(model_dir.relative_to(self.root)) if model_dir.is_relative_to(self.root) else model_dir.name
                    if model == '.':
                        model = model_dir.name
                    key = hashlib.sha256((folder + '/' + identity).encode()).hexdigest()[:24]
                    results = result_groups.get(identity, [])
                    edited = edited_groups.get(identity)
                    results.sort(key=lambda x: (x['version'] != 'original', natural_key(x['version']), x['name']))
                    record = {'key': key, 'id': identity, 'folder': folder, 'model': model, 'source': parent / source,
                              'source_error': error, 'edited': edited, 'results': results,
                              'best_path': parent / (identity + '_best.txt'),
                              'perfect_path': parent / (identity + '_perfect.txt'),
                              'perfect_image': parent / (identity + '_perfect.png'),
                              'rejected_path': parent / (identity + '_all_rejected.txt')}
                    records[key] = record
                    assets.add(record['source'])
                    assets.add(record['perfect_image'])
                    if edited is not None:
                        assets.add(edited)
                    assets.update(x['path'] for x in results)
            self.records = dict(sorted(records.items(), key=lambda kv: (natural_key(kv[1]['folder']), natural_key(kv[1]['id']))))
            self.assets = assets

    def read_annotation(self, path):
        if path.is_symlink():
            raise ReviewError('标注文件是符号链接,已拒绝访问', 409)
        try:
            data = path.read_bytes()
        except FileNotFoundError:
            return None, 'missing'
        if len(data) > 8192:
            raise ReviewError('标注文件异常,大小超过 8 KB', 409)
        return data.decode('utf-8').strip(), hashlib.sha256(data).hexdigest()

    def annotation_state(self, record):
        best, best_revision = self.read_annotation(record['best_path'])
        rejected, rejected_revision = self.read_annotation(record['rejected_path'])
        # Keep revisions compatible with existing pages until a rejection is saved.
        revision = best_revision if rejected_revision == 'missing' else hashlib.sha256(
            ('best:' + best_revision + '|rejected:' + rejected_revision).encode()).hexdigest()
        perfect, perfect_revision = self.read_annotation(record['perfect_path'])
        image = record['perfect_image']
        if image.is_symlink():
            raise ReviewError('修复图片是符号链接,已拒绝访问', 409)
        image_revision = hashlib.sha256(image.read_bytes()).hexdigest() if image.exists() else 'missing'
        if perfect_revision != 'missing' or image_revision != 'missing':
            revision = hashlib.sha256((revision + '|perfect:' + perfect_revision + '|image:' + image_revision).encode()).hexdigest()
        return best, rejected, revision

    def media(self, path):
        if path is None:
            return None
        try:
            stat = path.stat()
        except FileNotFoundError:
            return None
        relative = str(path.relative_to(self.root))
        return '/media?path=' + quote(relative, safe='') + f'&v={stat.st_mtime_ns}-{stat.st_size}'

    def describe(self, record):
        value, rejected, revision = self.annotation_state(record)
        results = [{'name': x['name'], 'version': x['version'], 'url': self.media(x['path'])}
                   for x in record['results'] if self._inside_file(x['path'])]
        valid = value is not None and value in {x['name'] for x in results}
        perfect, _ = self.read_annotation(record['perfect_path'])
        valid_rejection = rejected in REJECTION_REASONS
        conflict = valid and valid_rejection
        return {'key': record['key'], 'id': record['id'], 'folder': record['folder'], 'model': record['model'],
                'source_url': self.media(record['source']), 'source_error': record['source_error'],
                'edited_url': self.media(record['edited']), 'results': results,
                'best': value if valid and not conflict else None,
                'perfect': perfect if valid and perfect == value and not conflict else None,
                'perfect_url': self.media(record['perfect_image']) if valid and perfect == value and not conflict else None,
                'rejection': rejected if valid_rejection and not conflict else None,
                'invalid_best': bool(value and not valid),
                'invalid_rejection': rejected is not None and not valid_rejection,
                'annotation_conflict': conflict,
                'revision': revision, 'best_file': str(record['best_path'].relative_to(self.root)),
                'rejected_file': str(record['rejected_path'].relative_to(self.root))}

    def state(self):
        with self.lock:
            items = [self.describe(x) for x in self.records.values() if self._inside_file(x['source'])]
            stats = {'total': len(items), 'done': sum(bool(x['best'] or x['rejection']) for x in items),
                     'rejected': sum(x['rejection'] is not None for x in items),
                     'pending': sum(bool(x['results']) and not (x['best'] or x['rejection']) for x in items),
                     'no_results': sum(not x['results'] for x in items)}
            return {'items': items, 'stats': stats, 'dataset': str(self.root)}

    def choose(self, key, result_name, expected_revision, clear=False):
        return self.save_annotation(key, expected_revision, 'clear' if clear else 'best', result_name)

    def reject(self, key, reason, expected_revision):
        if not isinstance(reason, str) or reason not in REJECTION_REASONS:
            raise ReviewError('请选择“结果都不满意”或“edited 不满意”')
        return self.save_annotation(key, expected_revision, 'rejected', reason)

    @staticmethod
    def write_annotation(path, value):
        temporary = None
        try:
            with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', newline='\n',
                    prefix='.' + path.name + '.', suffix='.tmp', dir=path.parent, delete=False) as stream:
                temporary = Path(stream.name)
                stream.write(value + '\n')
                stream.flush()
                os.fsync(stream.fileno())
            os.replace(temporary, path)
        finally:
            if temporary is not None:
                temporary.unlink(missing_ok=True)

    def save_annotation(self, key, expected_revision, kind, value, png=None):
        with self.lock:
            record = self.records.get(key)
            if record is None or not self._inside_file(record['source']):
                raise ReviewError('条目或 source 已被移除,请刷新目录', 404)
            _, _, revision = self.annotation_state(record)
            if not isinstance(expected_revision, str) or revision != expected_revision:
                raise ReviewError('该标注已在其他页面被修改,请刷新后重试', 409)
            best_path, rejected_path = record['best_path'], record['rejected_path']
            perfect_path, perfect_image = record['perfect_path'], record['perfect_image']
            for path in (best_path, rejected_path, perfect_path, perfect_image):
                if path.parent.resolve() != record['source'].parent.resolve():
                    raise ReviewError('无效的保存目录')
            paths = (best_path, rejected_path, perfect_path, perfect_image)
            previous = {path: path.read_bytes() if path.exists() else None for path in paths}
            try:
                if kind == 'clear':
                    best_path.unlink(missing_ok=True)
                    rejected_path.unlink(missing_ok=True)
                elif kind in {'best', 'perfect', 'repair'}:
                    chosen = next((x for x in record['results'] if x['name'] == value), None)
                    if chosen is None or not self._inside_file(chosen['path']):
                        raise ReviewError('请选择当前条目中存在的 result 图片')
                    if kind == 'repair':
                        image_data = decode_skin_png(png)
                        self.write_bytes(perfect_image, image_data)
                    else:
                        perfect_image.unlink(missing_ok=True)
                    if kind in {'perfect', 'repair'}:
                        self.write_annotation(perfect_path, value)
                    else:
                        perfect_path.unlink(missing_ok=True)
                    self.write_annotation(best_path, value)
                    rejected_path.unlink(missing_ok=True)
                elif kind == 'rejected':
                    if value == 'edited_unsatisfied' and (record['edited'] is None or not self._inside_file(record['edited'])):
                        raise ReviewError('此条目的 edited 图片不存在,请刷新目录')
                    if value == 'result_unsatisfied' and not any(self._inside_file(x['path']) for x in record['results']):
                        raise ReviewError('此条目暂无 result 图片')
                    self.write_annotation(rejected_path, value)
                    best_path.unlink(missing_ok=True)
                else:
                    raise ReviewError('无效的标注操作')
                if kind in {'clear', 'rejected'}:
                    perfect_path.unlink(missing_ok=True)
                    perfect_image.unlink(missing_ok=True)
            except OSError:
                # Restore already-written files if a later write/remove fails.
                for path, data in previous.items():
                    current = path.read_bytes() if path.exists() else None
                    if current != data:
                        if data is None:
                            path.unlink(missing_ok=True)
                        else:
                            self.write_bytes(path, data)
                raise
            return self.describe(record)

    @staticmethod
    def write_bytes(path, value):
        temporary = None
        try:
            with tempfile.NamedTemporaryFile(prefix='.' + path.name, dir=path.parent, delete=False) as stream:
                temporary = Path(stream.name)
                stream.write(value)
                stream.flush()
                os.fsync(stream.fileno())
            os.replace(temporary, path)
        finally:
            if temporary is not None:
                temporary.unlink(missing_ok=True)

    def resolve_media(self, relative):
        path = self.root / relative
        if path not in self.assets or not self._inside_file(path):
            raise ReviewError('图片不存在', 404)
        return path


def decode_skin_png(value):
    """Validate the complete PNG produced by canvas, including CRC and pixel payload."""
    try:
        if not isinstance(value, str) or not value.startswith('data:image/png;base64,'):
            raise ValueError()
        data = base64.b64decode(value.split(',', 1)[1], validate=True)
        if len(data) > 131072 or data[:8] != b'\x89PNG\r\n\x1a\n':
            raise ValueError()
        offset, compressed, channels, ended = 8, bytearray(), None, False
        while offset < len(data):
            size = struct.unpack('>I', data[offset:offset + 4])[0]
            tag = data[offset + 4:offset + 8]
            payload = data[offset + 8:offset + 8 + size]
            crc = struct.unpack('>I', data[offset + 8 + size:offset + 12 + size])[0]
            if zlib.crc32(tag + payload) != crc:
                raise ValueError()
            if offset == 8:
                if tag != b'IHDR' or size != 13:
                    raise ValueError()
                width, height, depth, color, compression, filtering, interlace = struct.unpack('>IIBBBBB', payload)
                if (width, height, depth, compression, filtering, interlace) != (64, 64, 8, 0, 0, 0) or color not in (2, 6):
                    raise ValueError()
                channels = 4 if color == 6 else 3
            elif tag == b'IHDR':
                raise ValueError()
            if tag == b'IDAT':
                compressed.extend(payload)
            offset += size + 12
            if tag == b'IEND':
                if size or offset != len(data):
                    raise ValueError()
                ended = True
                break
        decoder = zlib.decompressobj()
        raw = decoder.decompress(bytes(compressed), 16449)
        if not ended or not decoder.eof or decoder.unused_data or len(raw) != 64 * (64 * channels + 1):
            raise ValueError()
        if any(raw[i] > 4 for i in range(0, len(raw), 64 * channels + 1)):
            raise ValueError()
        return data
    except (ValueError, TypeError, struct.error, zlib.error, binascii.Error):
        raise ReviewError('请提交有效的 64×64 PNG 皮肤')


def make_server(dataset, host, port):
    class Handler(BaseHTTPRequestHandler):
        server_version = 'DDJReview/1.0'

        def send(self, status, data, content_type='application/json; charset=utf-8', cache='no-store'):
            if not isinstance(data, bytes):
                data = json.dumps(data, ensure_ascii=False).encode()
            self.send_response(status)
            self.send_header('Content-Type', content_type)
            self.send_header('Content-Length', str(len(data)))
            self.send_header('Cache-Control', cache)
            self.send_header('X-Content-Type-Options', 'nosniff')
            self.send_header('Referrer-Policy', 'same-origin')
            self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'")
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):
            try:
                request = urlsplit(self.path)
                if request.path == '/api/state':
                    return self.send(200, dataset.state())
                if request.path == '/api/health':
                    return self.send(200, {'status': 'ok', 'sources': len(dataset.records)})
                if request.path == '/media':
                    relative = parse_qs(request.query).get('path', [''])[0]
                    with dataset.lock:
                        path = dataset.resolve_media(relative)
                    return self.send(200, path.read_bytes(), mimetypes.guess_type(path.name)[0] or 'application/octet-stream', 'private, max-age=3600')
                name = 'index.html' if request.path == '/' else unquote(request.path).lstrip('/')
                path = (STATIC_DIR / name).resolve()
                if not path.is_relative_to(STATIC_DIR) or not path.is_file():
                    raise ReviewError('文件不存在', 404)
                return self.send(200, path.read_bytes(), mimetypes.guess_type(path.name)[0] or 'application/octet-stream')
            except (ReviewError, OSError, UnicodeError) as error:
                self.send(getattr(error, 'status', 500), {'error': str(error)})

        def do_POST(self):
            try:
                origin = self.headers.get('Origin')
                if origin and urlsplit(origin).netloc != self.headers.get('Host'):
                    raise ReviewError('不允许跨站修改', 403)
                if self.headers.get('X-Annotation-Client') != 'ddj-review':
                    raise ReviewError('缺少客户端标识', 403)
                if self.headers.get_content_type() != 'application/json':
                    raise ReviewError('需要 JSON 请求')
                length = int(self.headers.get('Content-Length', '0'))
                if not 0 <= length <= 200000:
                    raise ReviewError('请求过大', 413)
                body = json.loads(self.rfile.read(length) or b'{}')
                if not isinstance(body, dict):
                    raise ReviewError('无效请求')
                if self.path == '/api/refresh':
                    dataset.scan()
                    return self.send(200, dataset.state())
                if self.path not in {'/api/choose', '/api/clear', '/api/reject', '/api/perfect', '/api/repair'}:
                    raise ReviewError('接口不存在', 404)
                if not isinstance(body.get('key'), str):
                    raise ReviewError('缺少条目编号')
                if self.path in {'/api/perfect', '/api/repair'}:
                    item = dataset.save_annotation(body['key'], body.get('revision'), self.path.rsplit('/', 1)[1], body.get('result'), body.get('png'))
                elif self.path == '/api/reject':
                    item = dataset.reject(body['key'], body.get('reason'), body.get('revision'))
                else:
                    item = dataset.choose(body['key'], body.get('result'), body.get('revision'), self.path == '/api/clear')
                return self.send(200, {'item': item})
            except (ReviewError, OSError, ValueError, UnicodeError) as error:
                self.send(getattr(error, 'status', 400), {'error': str(error)})

    server = ThreadingHTTPServer((host, port), Handler)
    server.daemon_threads = True
    return server


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=APP_DIR.parent)
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', type=int, default=8765)
    args = parser.parse_args()
    dataset = Dataset(args.root)
    server = make_server(dataset, args.host, args.port)
    print(json.dumps({'url': f'http://{args.host}:{server.server_port}', 'root': str(dataset.root),
                      'stats': dataset.state()['stats']}, ensure_ascii=False), flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()


if __name__ == '__main__':
    main()