File size: 3,398 Bytes
3d46bcf
 
 
b5af7d6
 
3d46bcf
 
 
 
 
b5af7d6
3d46bcf
 
 
b5af7d6
3d46bcf
 
 
b5af7d6
3d46bcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5af7d6
 
 
 
 
 
 
 
 
 
 
 
3d46bcf
 
 
 
 
 
 
b5af7d6
3d46bcf
 
 
 
 
 
 
b5af7d6
 
 
 
3d46bcf
 
 
 
 
 
 
 
 
 
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
import base64
import io
import warnings
from threading import BoundedSemaphore
from typing import Literal

import cv2
import numpy as np
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from pathlib import Path
from PIL import Image, ImageOps

from .review import review_pair

app = FastAPI(title='Iris registration POC')
Image.MAX_IMAGE_PIXELS = 30_000_000
processing_slots = BoundedSemaphore(1)


def decode(data):
    try:
        with warnings.catch_warnings():
            warnings.simplefilter('error', Image.DecompressionBombWarning)
            with Image.open(io.BytesIO(data)) as image:
                if image.width * image.height > 30_000_000 or min(image.size) < 64:
                    raise ValueError('Image must be at least 64px per side and at most 30 megapixels.')
                image = ImageOps.exif_transpose(image).convert('RGB')
                return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
    except Exception as exc:
        raise ValueError('Invalid or oversized image. Use JPEG or PNG up to 30 megapixels.') from exc


@app.get('/api/health')
def health():
    return {'status': 'ok'}


@app.post('/api/register')
def registration(reference: UploadFile = File(...), moving: UploadFile = File(...), exposure: bool = Form(True), local: bool = Form(True), engine: Literal['classical', 'learned'] = Form('classical'), iris_crop_confirmed: bool = Form(False)):
    if engine == 'learned' and not iris_crop_confirmed:
        raise HTTPException(status_code=422, detail='Confirm both images are equally sized square crops centered on the iris before using experimental alignment.')
    if not processing_slots.acquire(blocking=False):
        raise HTTPException(status_code=503, detail='Another pair is being processed. Please retry shortly.', headers={'Retry-After':'10'})
    try:
        return process_pair(reference, moving, exposure, local, engine)
    finally:
        processing_slots.release()


def process_pair(reference, moving, exposure, local, engine):
    try:
        images = []
        for upload in (reference, moving):
            data = upload.file.read(25_000_001)
            if len(data) > 25_000_000:
                raise ValueError('Each upload must be under 25 MB.')
            images.append(decode(data))
        result = review_pair(*images, exposure=exposure, local=local, engine=engine)
        encoded = {}
        for key, value in result.items():
            if key != 'metrics':
                ok, buf = cv2.imencode('.png', value)
                if not ok:
                    raise ValueError('Could not encode output.')
                encoded[key] = 'data:image/png;base64,' + base64.b64encode(buf).decode()
        return JSONResponse({'images': encoded, 'metrics': result['metrics']})
    except RuntimeError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc
    except (ValueError, cv2.error) as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc


root = Path(__file__).resolve().parents[1]
reports = root / 'reports'
if reports.exists():
    app.mount('/benchmark', StaticFiles(directory=reports, html=True), name='benchmark')
dist = root / 'frontend' / 'dist'
if dist.exists():
    app.mount('/', StaticFiles(directory=dist, html=True), name='frontend')