|
| 1 | +import ast |
| 2 | +import pathlib |
| 3 | + |
| 4 | +# Requirements |
| 5 | +import jinja2 |
| 6 | +import numpy as np |
| 7 | +import PIL.Image |
| 8 | +from fastapi import Depends, FastAPI, Request, responses |
| 9 | +from fastapi.responses import HTMLResponse |
| 10 | +from fastapi.templating import Jinja2Templates |
| 11 | + |
| 12 | +# Project |
| 13 | +from caterva2.services import db |
| 14 | +from caterva2.services.server import get_container, optional_user, resize_image |
| 15 | +from caterva2.services.server import templates as sub_templates |
| 16 | + |
| 17 | +app = FastAPI() |
| 18 | +BASE_DIR = pathlib.Path(__file__).resolve().parent |
| 19 | +templates = Jinja2Templates(directory=BASE_DIR / "templates") |
| 20 | +templates.env.loader = jinja2.ChoiceLoader( |
| 21 | + [ |
| 22 | + templates.env.loader, # Preserve the original loader |
| 23 | + sub_templates.env.loader, # Add the sub-templates loader |
| 24 | + ] |
| 25 | +) |
| 26 | + |
| 27 | +name = "image" # Identifies the plugin |
| 28 | +label = "Image" |
| 29 | +contenttype = "image" |
| 30 | + |
| 31 | + |
| 32 | +urlbase = None |
| 33 | + |
| 34 | + |
| 35 | +def init(urlbase_): |
| 36 | + global urlbase |
| 37 | + urlbase = urlbase_ |
| 38 | + |
| 39 | + |
| 40 | +def url(path: str) -> str: |
| 41 | + return f"{urlbase}/{path}" |
| 42 | + |
| 43 | + |
| 44 | +def guess(path: pathlib.Path, meta) -> bool: |
| 45 | + """Does dataset (given path and metadata) seem of this content type?""" |
| 46 | + if not hasattr(meta, "dtype"): |
| 47 | + return False # not an array |
| 48 | + |
| 49 | + dtype = meta.dtype |
| 50 | + if dtype is None: |
| 51 | + return False |
| 52 | + |
| 53 | + # Structured dtype |
| 54 | + if isinstance(dtype, str) and dtype.startswith("["): |
| 55 | + dtype = eval(dtype) # TODO Make it safer |
| 56 | + |
| 57 | + # Sometimes dtype is a tuple (e.g. ('<f8', (10,))), and this seems a safe way to handle it |
| 58 | + try: |
| 59 | + dtype = np.dtype(dtype) |
| 60 | + except (ValueError, TypeError): |
| 61 | + dtype = np.dtype(ast.literal_eval(dtype)) |
| 62 | + if dtype.kind != "u": |
| 63 | + return False |
| 64 | + |
| 65 | + shape = tuple(meta.shape) |
| 66 | + if len(shape) == 3: |
| 67 | + return True # grayscale |
| 68 | + |
| 69 | + # RGB(A) |
| 70 | + return len(shape) == 4 and shape[-1] in (3, 4) |
| 71 | + |
| 72 | + |
| 73 | +@app.get("/display/{path:path}", response_class=HTMLResponse) |
| 74 | +async def display( |
| 75 | + request: Request, |
| 76 | + # Path parameters |
| 77 | + path: pathlib.Path, |
| 78 | + user: db.User = Depends(optional_user), |
| 79 | +): |
| 80 | + ndim = 0 |
| 81 | + i = 0 |
| 82 | + |
| 83 | + array = await get_container(path, user) |
| 84 | + height, width = (x for j, x in enumerate(array.shape[:3]) if j != ndim) |
| 85 | + |
| 86 | + base = url(f"plugins/{name}") |
| 87 | + href = f"{base}/image/{path}?{ndim=}&{i=}" |
| 88 | + |
| 89 | + context = { |
| 90 | + "href": href, |
| 91 | + "shape": array.shape, |
| 92 | + "width": width, |
| 93 | + "height": height, |
| 94 | + } |
| 95 | + return templates.TemplateResponse(request, "display.html", context=context) |
| 96 | + |
| 97 | + |
| 98 | +async def __get_image(path, user, ndim, i): |
| 99 | + array = await get_container(path, user) |
| 100 | + index = [slice(None) for x in array.shape] |
| 101 | + index[ndim] = slice(i, i + 1, 1) |
| 102 | + content = array[tuple(index)].squeeze() |
| 103 | + if content.dtype.kind != "u": |
| 104 | + content = (content - content.min()) / (content.max() - content.min()) # normalise to 0-1 |
| 105 | + content = (content * 255).astype(np.uint8) |
| 106 | + return PIL.Image.fromarray( |
| 107 | + content, mode="RGB" + ("A" if content.shape[-1] == 4 else "") if content.ndim == 3 else "L" |
| 108 | + ) |
| 109 | + |
| 110 | + |
| 111 | +@app.get("/image/{path:path}") |
| 112 | +async def image_file( |
| 113 | + request: Request, |
| 114 | + # Path parameters |
| 115 | + path: pathlib.Path, |
| 116 | + # Query parameters |
| 117 | + ndim: int, |
| 118 | + i: int, |
| 119 | + width: int | None = None, |
| 120 | + user: db.User = Depends(optional_user), |
| 121 | +): |
| 122 | + img = await __get_image(path, user, ndim, i) |
| 123 | + img_file = resize_image(img, width) |
| 124 | + |
| 125 | + def iterfile(): |
| 126 | + yield from img_file |
| 127 | + |
| 128 | + return responses.StreamingResponse(iterfile(), media_type="image/png") |
0 commit comments