Spaces:
Sleeping

ohgnues's picture
Upload 2 files
944265a verified
Raw History Blame Contribute Delete
8.47 kB
from collections import Counter
from pathlib import Path
import datetime as dt, hashlib, hmac, json, os, random, re, secrets, tempfile, threading, uuid, zipfile
from flask import Flask, abort, jsonify, render_template, request, send_file, session
root=Path(__file__).resolve().parent
assetzip=root/'study_assets.zip'
buildstamp=hashlib.sha256(assetzip.read_bytes()).hexdigest()[:18]
builddir=Path(tempfile.gettempdir())/('image-study-'+buildstamp)
with zipfile.ZipFile(assetzip) as z:
for p in z.namelist():
if not re.fullmatch(r'(images/[0-9a-f]{32}\.webp|cases\.json|templates/index\.html)',p):
raise RuntimeError('Unexpected asset path')
z.extractall(builddir)
cases_path=Path(os.environ.get('STUDY_MANIFEST',builddir/'cases.json'))
assets=cases_path.parent
cases=json.loads(cases_path.read_text())
byid={c['id']:c for c in cases}
version='otter-score-v2-'+hashlib.sha256(cases_path.read_bytes()).hexdigest()[:8]
if Counter(c['task'] for c in cases)!=dict(sr=20,cdd=20) or len(byid)!=40:
raise RuntimeError('Study requires exactly 20 SR and 20 CDD-11 cases')
for c in cases:
if set(c['methods']) not in ({'OTTER','TSD-SR','PiSA-SR','AddSR'},{'OTTER','MoCE-IR','BaryIR','MIRAGE'}):
raise RuntimeError('Four named methods required per case')
if not all((assets/p).is_file() for p in [c['gt'],*c['methods'].values()]):
raise RuntimeError('Missing image assets')
studies={version:(cases,assets)}
current=version
for prefix, filename in [('otter-score-v3-', 'study_remix.zip'),('otter-score-v4-', 'study_refresh.zip'),('otter-score-v5-', 'study_final_sr.zip')]:
delta=root/filename
if not delta.is_file():continue
raw=delta.read_bytes()
remix_dir=Path(tempfile.gettempdir())/('image-study-remix-'+hashlib.sha256(raw).hexdigest()[:18])
with zipfile.ZipFile(delta) as z:
if any(not re.fullmatch(r'(images/[0-9a-f]{32}\.webp|cases\.json)',p) for p in z.namelist()):
raise RuntimeError('Unexpected remix asset path')
z.extractall(remix_dir)
manifest=(remix_dir/'cases.json').read_bytes()
next_cases=json.loads(manifest)
if Counter(c['task'] for c in next_cases)!=dict(sr=20,cdd=20) or len({c['id'] for c in next_cases})!=40:
raise RuntimeError('Remix requires 20 SR and 20 CDD-11 cases')
for c in next_cases:
names={'sr':{'OTTER','TSD-SR','PiSA-SR','AddSR'},'cdd':{'OTTER','MoCE-IR','BaryIR','MIRAGE'}}
if set(c['methods'])!=names[c['task']] or any(not re.fullmatch(r'images/[0-9a-f]{32}\.webp',p) or not ((remix_dir/p).is_file() or any((d/p).is_file() for _,d in studies.values())) for p in [c['gt'],*c['methods'].values()]):
raise RuntimeError('Invalid remix asset')
current=prefix+hashlib.sha256(manifest).hexdigest()[:8]
studies[current]=(next_cases,remix_dir)
app=Flask(__name__,template_folder=str(builddir/'templates'))
hf=bool(os.environ.get('SPACE_ID'))
mounted=Path('/data') if hf and os.path.ismount('/data') else None
mirror=bool(os.environ.get('HF_RESPONSE_BUCKET') and os.environ.get('HF_DATASET_REPO') and os.environ.get('BUCKET_TOKEN') and os.environ.get('HF_TOKEN'))
write_lock=threading.Lock()
probed=False
key=os.environ.get('STUDY_SECRET')
if not key and mounted:
sk=mounted/'.session-secret'
if not sk.exists():
try:
with sk.open('x') as f: f.write(secrets.token_hex(32))
except FileExistsError: pass
key=sk.read_text().strip()
app.secret_key=key or secrets.token_hex(32)
app.config.update(SESSION_COOKIE_HTTPONLY=True,SESSION_COOKIE_SAMESITE='None' if hf else 'Lax',SESSION_COOKIE_PARTITIONED=hf,
SESSION_COOKIE_SECURE=hf,MAX_CONTENT_LENGTH=32000)
# URL fragments and citation metadata are not sent to respondents.
def schedule(sid,sv=version):
salt=hmac.new(app.secret_key.encode(),f'{sid}:{sv}'.encode(),hashlib.sha256).hexdigest()
rng=random.Random(salt)
order=[]
for task in ['sr','cdd']:
picks=[c for c in studies[sv][0] if c['task']==task]; rng.shuffle(picks)
for c in picks:
methods=sorted(c['methods']);rng.shuffle(methods)
order.append((c,methods))
return order
def participant(sid):
try:return str(uuid.UUID(sid))
except (TypeError,ValueError,AttributeError):abort(400)
@app.get('/')
def home():
return send_file(root/'study_ui.html',mimetype='text/html',max_age=0) if (root/'study_ui.html').is_file() else render_template('index.html')
@app.get('/api/start')
def start():
sid=participant(request.args.get('pid'))
out=[]
prefix='/image' if current==version else f'/image/{current}'
for n,(c,methods) in enumerate(schedule(sid,current)):
out.append(dict(id=c['id'],task=c['task'],gt=f'{prefix}/{sid}/{n}/0',images=[f'{prefix}/{sid}/{n}/{i}' for i in range(1,5)]))
return jsonify(session=sid,cases=out,version=current)
@app.get('/image/<sid>/<int:n>/<int:k>')
@app.get('/image/<sv>/<sid>/<int:n>/<int:k>')
def tile(sid,n,k,sv=version):
if sv not in studies or not 0<=n<40 or not 0<=k<=4:abort(404)
c,ms=schedule(participant(sid),sv)[n]
path=c['gt'] if not k else c['methods'][ms[k-1]]
image_path=studies[sv][1]/path
if not image_path.is_file():image_path=next((d/path for _,d in studies.values() if (d/path).is_file()),None)
if image_path is None:abort(404)
response=send_file(image_path,mimetype='image/webp',conditional=True)
response.cache_control.no_store=True
return response
def persist(sid,doc,test=False):
raw=json.dumps(doc,sort_keys=True,separators=(',',':')).encode()
digest=hashlib.sha256(raw).hexdigest()
relative=Path('responses')/('storage-selftest-otter' if test else doc['version'])/sid/f'{digest}.json'
if mirror:
from bucket_storage import save_payload, initialize
initialize()
save_payload(raw,str(relative))
return
if hf and not mounted: raise RuntimeError('Persistent responses volume is not mounted')
target=(mounted if hf else Path(os.environ.get('LOCAL_STUDY_VOTES',root/'_local_test_votes')))/relative
with write_lock:
target.parent.mkdir(parents=True,exist_ok=True)
if not target.is_file() or target.read_bytes()!=raw:target.write_bytes(raw)
if target.read_bytes()!=raw:raise RuntimeError('Response read-back mismatch')
@app.post('/api/submit')
def submit():
data=request.get_json(silent=True)
if not isinstance(data,dict):abort(400)
sv=data.get('version')
if not isinstance(sv,str) or sv not in studies:abort(400)
sid=participant(data.get('participant_id'))
match=next(((c,ms) for c,ms in schedule(sid,sv) if c['id']==data.get('sample_id')),None)
if match is None:abort(400)
c,ms=match
scores=data.get('scores')
if not isinstance(scores,dict) or set(scores)!= {'fidelity','perceptual'}:abort(400)
for per_slot in scores.values():
if not isinstance(per_slot,dict) or set(per_slot)!=set('ABCD') or any(type(v)!=int or not 1<=v<=5 for v in per_slot.values()):abort(400)
stamp=data.get('submitted_at')
if not isinstance(stamp,str) or len(stamp)>40:abort(400)
mapped={k:{m:scores[k][l] for l,m in zip('ABCD',ms)} for k in scores}
doc=dict(version=sv,participant_id=sid,sample_id=c['id'],dataset=c['task'],submitted_at=stamp,mapping=dict(zip('ABCD',ms)),scores=scores,scores_by_model=mapped)
try:persist(sid,doc)
except Exception:
app.logger.exception('Study submission not persisted')
return jsonify(error='Storage unavailable. The browser will retry.'),503
return jsonify(saved=True)
@app.get('/health')
def healthy(): return jsonify(ok=True,count=len(cases),study_version=current,storage_verified=probed,storage='bucket+dataset' if mirror else ('mounted-private-bucket' if mounted else 'local'))
@app.after_request
def headers(r):
r.headers['X-Content-Type-Options']='nosniff'
if request.path.startswith('/api/'):r.headers['Cache-Control']='no-store'
return r
if __name__=='__main__':
if hf:
import spaces
# Same compatibility registration as the existing DOMINO Space. Never called.
@spaces.GPU(duration=1)
def _noop():
pass
import gradio as gr
with gr.Blocks() as compatibility:
gr.Markdown('Image restoration study service')
compatibility.launch(server_name='127.0.0.1',server_port=8765,prevent_thread_lock=True,show_api=False,quiet=True)
probe_id=str(uuid.uuid4())
try:
persist(probe_id,dict(synthetic=True,test='otter-startup-storage-readback',run=probe_id),test=True)
probed=True
print('OTTER durable storage self-test: PASS '+probe_id,flush=True)
except Exception:
app.logger.exception('OTTER durable storage self-test failed')
# Mark ready only after the write/read-back probe on the mounted volume.
from waitress import serve
serve(app,host='0.0.0.0',port=7860,threads=8)
else:
app.run(host='127.0.0.1',port=7860)