VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 4)
9d57416 verified
Raw History Blame Contribute Delete
5.69 kB
"""Fingerprint-checked segment review import reader. Imported views remain distinct from ActivityProposal."""
import hashlib
from collections import OrderedDict
import threading
import json
from pathlib import Path
from .errors import require
from .schema import validate
MANIFEST='review-import.json'
IMPORT_SCHEMA='console-review-import/2'
_CACHE=OrderedDict()
_LOCK=threading.Lock()
# 段页、每次证明请求都先核指纹;整算 sha256(含 private20hz.npz)在负载高的 GPU 上要几十秒。
# 文件的 (mtime_ns, size, ino) 没变就沿用上次核过的结果,与 question_review.listing_key 同一判法。
_VERIFIED=OrderedDict()
_QUESTIONS=OrderedDict()
def _stamps(paths):
out=[]
for path in paths:
st=Path(path).stat()
out.append((str(path),st.st_mtime_ns,st.st_size,st.st_ino))
return tuple(out)
def sha(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for block in iter(lambda:f.read(1024*1024),b''):h.update(block)
return h.hexdigest()
def verify_import(directory):
directory=Path(directory)
require((directory/MANIFEST).is_file(),'REVIEW_IMPORT_SCHEMA','缺少现行导入清单,须先离线转换')
manifest=json.loads((directory/MANIFEST).read_text())
require(manifest.get('schema')==IMPORT_SCHEMA,'REVIEW_IMPORT_SCHEMA','未知源数据导入版本')
require((directory/'view.json').stat().st_size<=3_000_000,'RESPONSE_TOO_LARGE','逐段响应超过3 MB')
for name in manifest['files']:
require(name in ('view.json','basemap.png','questions.json'),'REVIEW_IMPORT_PATH','未知导入文件')
try:
key=(str(directory.resolve()),_stamps([directory/MANIFEST,*(directory/n for n in manifest['files']),*(r['path'] for r in manifest['inputs'].values())]))
except OSError:
key=None # 缺文件:照常逐个核,报出是哪一个
with _LOCK:
if key is not None and key in _VERIFIED:
return manifest
for name,ref in manifest['files'].items():
path=directory/name
require(path.resolve().parent==directory.resolve() and sha(path)==ref,'REVIEW_IMPORT_INTEGRITY','导入文件指纹不符:'+name)
for name,ref in manifest['inputs'].items():
require(sha(ref['path'])==ref['sha256'],'REVIEW_IMPORT_INPUT_INTEGRITY','原始输入指纹不符:'+name)
if key is not None:
with _LOCK:
_VERIFIED[key]=True
while len(_VERIFIED)>64:_VERIFIED.popitem(last=False)
return manifest
def read_import(directory, segment_id=None):
directory=Path(directory)
manifest=verify_import(directory)
key=(str(directory.resolve()),manifest['files']['view.json'])
with _LOCK:
cached=_CACHE.get(key)
# Keep immutable JSON in the cache. Parsing in C gives each consumer a fresh
# tree without recursively copying hundreds of thousands of scalar values.
source_text=cached if cached is not None else (directory/'view.json').read_text()
view=json.loads(source_text)
require(view['segment']['script_id']==manifest['inputs']['private20hz.npz']['sha256'],'REVIEW_IMPORT_IDENTITY','script_id必须为NPZ SHA')
# Source records without body yaw: forbid motion/camera direction standing in for it. Only the new generator declares
# yaw_source per actor in its script.json (hash-checked input case.json); only those actors may carry yaw_rad.
script=json.loads(Path(manifest['inputs']['case.json']['path']).read_text())
declared={a['id'] for a in script.get('actors',[]) if a.get('yaw_source') in ('travel_heading','planned')}
require(all(track['yaw_rad'] is None or aid in declared for aid,track in view['tracks'].items()),'REVIEW_IMPORT_BODY_YAW','源数据没有body yaw,禁止用运动或镜头方向代替;只有声明了 yaw_source 的生成器主体可带机身朝向')
status=view.get('review',{}).get('actual_arrangements_status')
if status=='generator_plan':
require(any(a.get('plan') for a in script.get('actors',[])),'REVIEW_IMPORT_ARRANGEMENT','声称有生成器计划,但 script.json 里没有 plan')
else:
require(status=='generator_not_emitted','REVIEW_IMPORT_ARRANGEMENT','生成器没有安排输出')
if cached is None:
validate(view)
with _LOCK:
_CACHE[key]=source_text
while len(_CACHE)>8:_CACHE.popitem(last=False)
if segment_id:
view['segment']['id']=segment_id
from urllib.parse import quote
view['basemap']['raster']['url']='/api/v1/segments/'+quote(segment_id,safe='')+'/basemap.png'
# 题号含 # 和 /(如 …/multi_ego.reframe#0),不编码时 # 后面被浏览器当成片段丢掉
for q in view['review']['questions']:q['proof_url']='/api/v1/segments/'+quote(segment_id,safe='')+'/questions/'+quote(q['id'],safe='')
return view,(directory/'basemap.png').read_bytes()
def question_detail(directory, candidate_id):
read_import(directory)
manifest=json.loads((Path(directory)/MANIFEST).read_text())
key=(str(Path(directory).resolve()),manifest['files']['questions.json'])
with _LOCK:
data=_QUESTIONS.get(key)
if data is None: # 一段几百道题,每次请求整份重解析太慢;按已核过的指纹缓存,给出去的是逐题新解析的副本
data={k:json.dumps(v,ensure_ascii=False) for k,v in json.loads((Path(directory)/'questions.json').read_text()).items()}
with _LOCK:
_QUESTIONS[key]=data
while len(_QUESTIONS)>8:_QUESTIONS.popitem(last=False)
require(candidate_id in data,'QUESTION_NOT_FOUND','题目未登记')
return json.loads(data[candidate_id])