"""Append-only local review notes, with source binding at save time.""" import datetime import fcntl import json import math import os from pathlib import Path import threading import uuid from embodied_pipeline.artifacts import digest, load from .segment_import import MANIFEST from .errors import require, ViewError from .registry import small_json from .path_mapping import mapping CATEGORIES = ('unnatural_motion', 'unusable_view', 'situation_missed', 'insufficient_interaction', 'other') MAX_NOTE_BYTES = 64_000 class Notes: def __init__(self, directory, registry, batches, path_mapping=None, questions=None): self.directory = Path(directory) if directory else None self.path_mapping = mapping(path_mapping) self.registry, self.batches, self.lock = registry, batches, threading.Lock() self.owner = None self.questions = questions def close(self): if self.owner: self.owner.close() self.owner = None def _entries(self, scope): require(type(scope) is dict and set(scope) in ({'segment_id'}, {'batch_id'}), 'NOTE_SCOPE', '意见必须选一个段或批') if 'segment_id' in scope: entry = self.registry.entries.get(scope['segment_id']) require(entry is not None, 'NOTE_SCOPE', '意见段号未登记') return [entry] return self.batches.entries(scope['batch_id']) def save(self, request): require(self.directory is not None, 'NOTES_NOT_CONFIGURED', '意见目录尚未配置') if type(request) is dict and request.get('schema') == 'question-review-request/1': return self.save_question(request) fields = {'scope', 'span_s', 'actor_ids', 'category', 'text', 'reviewer', 'expected_fingerprints'} require(type(request) is dict and set(request) == fields, 'NOTE_FIELDS', '意见字段不完整或含未知字段') entries = self._entries(request['scope']) require(request['category'] in CATEGORIES, 'NOTE_CATEGORY', '未知意见类别') for field, limit in (('text', 8000), ('reviewer', 128)): value = request[field] require(type(value) is str and 0 < len(value.strip()) <= limit, 'NOTE_TEXT', '文字/审阅者为空或过长') require(type(request['actor_ids']) is list and all(type(id) is str for id in request['actor_ids']) and len(set(request['actor_ids'])) == len(request['actor_ids']), 'NOTE_ACTORS', '主体列表无效') def source(entry): if (entry.directory/MANIFEST).is_file(): from .segment_import import read_import view,_=read_import(entry.directory,entry.id) return dict(actors=view['actors'],span_s=view['segment']['span_s'], identity=dict(generator_version=view['provenance']['generator_version'])),view['provenance']['artifact_sha256'] self.path_mapping.load(entry.directory/'artifact.json','ActivityProposal') return small_json(entry.directory/'script.json'),digest(entry.directory/'artifact.json') lineage, ids = [], set() for entry in entries: data,fingerprint=source(entry) ids.update(a['id'] for a in data['actors']) lineage.append({'segment_id': entry.id, 'artifact_sha256': fingerprint, 'generator_version': data['identity']['generator_version']}) require(set(request['actor_ids']) <= ids, 'NOTE_ACTORS', '意见引用未登记主体') expected = {r['segment_id']: r['artifact_sha256'] for r in lineage} require(request['expected_fingerprints'] == expected, 'NOTE_STALE', '意见与当前剧本指纹不一致,请重开页面') span = request['span_s'] if 'segment_id' in request['scope']: data,_=source(entries[0]) require(type(span) is list and len(span) == 2 and all(type(v) in (int, float) and math.isfinite(v) for v in span) and data['span_s'][0] <= span[0] <= span[1] <= data['span_s'][1], 'NOTE_TIME_RANGE', '意见时间区间越界') else: require(span is None, 'NOTE_TIME_RANGE', '批意见不指定单段时间区间') now = datetime.datetime.now().astimezone() record = {'schema': 'review-note/1', 'id': uuid.uuid4().hex, 'created_at': now.isoformat(), **{k: request[k] for k in fields if k != 'expected_fingerprints'}, 'provenance': lineage} return self._append(record, now) def save_question(self, request): from .schema import validate schema = json.loads((Path(__file__).parent/'contracts/question-review-request.schema.json').read_text()) validate(request, schema) for field in ('answer', 'reviewer'): require(0 < len(request[field].strip()) <= (8000 if field == 'answer' else 128), 'NOTE_TEXT', '作答与审阅人不能为空或过长') require(self.questions is not None, 'QUESTION_NOT_FOUND', '没有题目来源') require(self.questions.fingerprint(request['question_id']) == request['expected_fingerprint'], 'NOTE_STALE', '题目来源已变,请重开页面') now = datetime.datetime.now().astimezone() record = {k: v for k, v in request.items() if k not in ('schema', 'expected_fingerprint')} record.update(schema='question-review/1', id=uuid.uuid4().hex, created_at=now.isoformat(), source_sha256=request['expected_fingerprint']) return self._append(record, now) def _append(self, record, now): encoded = (json.dumps(record, ensure_ascii=False, separators=(',', ':'), allow_nan=False) + '\n').encode() require(len(encoded) <= MAX_NOTE_BYTES, 'NOTE_TEXT', '意见超过64KB') with self.lock: self.directory.mkdir(parents=True, exist_ok=True) if self.owner is None: owner = (self.directory / '.writer.lock').open('a+b') try: fcntl.flock(owner, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: owner.close() raise ViewError('NOTES_BUSY', '意见目录已有写入服务') self.owner = owner with (self.directory / (now.date().isoformat() + '.jsonl')).open('ab') as stream: stream.write(encoded) stream.flush() os.fsync(stream.fileno()) return record def listing(self, segment_id=None, batch_id=None, question_id=None): require(not (segment_id and batch_id), 'NOTE_SCOPE', '一次只筛选段或批') if segment_id: self._entries({'segment_id': segment_id}) if batch_id: self._entries({'batch_id': batch_id}) rows, errors = [], [] if self.directory and self.directory.exists(): for path in sorted(self.directory.glob('*.jsonl')): with path.open(encoding='utf-8') as stream: for number, line in enumerate(stream, 1): try: require(len(line.encode()) <= MAX_NOTE_BYTES, 'NOTE_TEXT', '保存意见超过64KB') value = json.loads(line) require(value['schema'] in ('review-note/1', 'question-review/1'), 'NOTE_INVALID', '意见版本不匹配') if value['schema'] == 'question-review/1': require(all(isinstance(value[k], str) for k in ('question_id', 'reviewer', 'verdict')), 'NOTE_INVALID', '抽检记录缺少题号、审阅人或判定') if not segment_id and not batch_id and (not question_id or value['question_id'] == question_id): rows.append(value) continue if question_id: continue if segment_id and value['scope'].get('segment_id') != segment_id: continue if batch_id and value['scope'].get('batch_id') != batch_id and not any(p['segment_id'] in self.batches.members[batch_id] for p in value['provenance']): continue rows.append(value) except (ValueError, KeyError, TypeError, AttributeError) as exc: errors.append({'file': path.name, 'line': number, 'error': str(exc)}) # Files and lines are read in append order. Keep the history for readback, # but aggregate only each reviewer's latest judgement of each question. latest = {} for row in rows: if row['schema'] == 'question-review/1': latest[row['question_id'], row['reviewer']] = row active = [row for row in latest.values() if row['verdict'] != '作废'] return {'schema': 'review-notes/1', 'notes': rows, 'question_reviews': active, 'errors': errors}