Upload 5 files
Browse files- README.md +80 -3
- app.py +95 -0
- inference.py +177 -0
- model.py +95 -0
- requirements.txt +10 -0
README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
title: VAE Synethic CT Scan
|
| 4 |
+
sdk: gradio
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# VAE CT Slice Generator
|
| 8 |
+
|
| 9 |
+
Generate a **single 2D CT slice** from a segmentation mask using a VAE trained on 3D CT data. The model encodes your mask, decodes to 4 slices (3D volume), and returns **slice 2** as a 2D image for the web.
|
| 10 |
+
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
## How to use
|
| 14 |
+
|
| 15 |
+
1. **Upload a mask image** — Grayscale segmentation mask (any size; it will be resized to 256×256).
|
| 16 |
+
2. **Click Run** — The model encodes the mask, decodes to 4 slices, and shows slice 2.
|
| 17 |
+
3. **Download** — Use the output image as needed.
|
| 18 |
+
|
| 19 |
+
The model expects a single grayscale mask. It is duplicated into 4 “slices” (matching training), then the VAE encodes → decodes to 4 slices; only **slice index 2** is returned because the API cannot return 3D volumes.
|
| 20 |
+
|
| 21 |
+
---
|
| 22 |
+
|
| 23 |
+
## API
|
| 24 |
+
|
| 25 |
+
### `POST /generate`
|
| 26 |
+
|
| 27 |
+
Upload a mask image; get back a single slice as a data URI.
|
| 28 |
+
|
| 29 |
+
**Request:** `multipart/form-data` with a file (mask image).
|
| 30 |
+
|
| 31 |
+
**Response:**
|
| 32 |
+
```json
|
| 33 |
+
{
|
| 34 |
+
"image": "data:image/png;base64,..."
|
| 35 |
+
}
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
### `POST /predict`
|
| 39 |
+
|
| 40 |
+
Upload a mask image; get back the slice as base64 PNG.
|
| 41 |
+
|
| 42 |
+
**Request:** `multipart/form-data` with a file (mask image).
|
| 43 |
+
|
| 44 |
+
**Response:**
|
| 45 |
+
```json
|
| 46 |
+
{
|
| 47 |
+
"image": "<base64 PNG string>",
|
| 48 |
+
"slice_index": 2
|
| 49 |
+
}
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
## Model & input/output
|
| 55 |
+
|
| 56 |
+
- **Model:** VAE trained on 3D CT data (4-channel input/output, 256×256).
|
| 57 |
+
- **Input (training):** Label/mask as 4 slices `(1, 4, 256, 256)`. This Space accepts one grayscale mask, resizes to 256×256, normalizes to [0, 1], and duplicates it to 4 slices.
|
| 58 |
+
- **Output (model):** `decode(embedding)` has shape `(1, 4, 256, 256)` (4 slices). This Space returns **one slice** (index 2) as a 2D PNG.
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## Environment (optional)
|
| 63 |
+
|
| 64 |
+
| Variable | Default | Description |
|
| 65 |
+
|------------------|---------|--------------------------------|
|
| 66 |
+
| `MODEL_REPO` | `tan200224/Synthetic-CT-Scan_VAE_Conditional` | Hugging Face repo with the model. |
|
| 67 |
+
| `MODEL_FILENAME` | `mask2pic_64model_47.pt` | Filename of the checkpoint. |
|
| 68 |
+
|
| 69 |
+
Set these in your Space **Settings → Variables and secrets** if you use a different repo or file.
|
| 70 |
+
|
| 71 |
+
---
|
| 72 |
+
|
| 73 |
+
## Run locally
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
pip install -r requirements.txt
|
| 77 |
+
python app.py
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
Open http://localhost:7860 for the Gradio UI; use `/generate` or `/predict` for the API.
|
app.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VAE Hugging Face Space app.
|
| 3 |
+
Upload a mask image -> encode -> decode -> return one slice (slice 2 of 4).
|
| 4 |
+
"""
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
import logging
|
| 8 |
+
from fastapi import FastAPI, HTTPException, UploadFile
|
| 9 |
+
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 13 |
+
from fastapi.responses import JSONResponse
|
| 14 |
+
import gradio as gr
|
| 15 |
+
from PIL import Image
|
| 16 |
+
import uvicorn
|
| 17 |
+
|
| 18 |
+
from inference import inference_to_png, OUTPUT_SLICE_INDEX
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# --- Gradio UI ---
|
| 22 |
+
def run_inference(mask: Image.Image) -> Image.Image:
|
| 23 |
+
if mask is None:
|
| 24 |
+
raise gr.Error("Please upload a mask image.")
|
| 25 |
+
png_bytes = inference_to_png(mask, slice_index=OUTPUT_SLICE_INDEX)
|
| 26 |
+
return Image.open(io.BytesIO(png_bytes)).convert("L")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
demo = gr.Interface(
|
| 30 |
+
fn=run_inference,
|
| 31 |
+
inputs=gr.Image(label="Mask (grayscale)", type="pil"),
|
| 32 |
+
outputs=gr.Image(label=f"Output slice {OUTPUT_SLICE_INDEX} of 4"),
|
| 33 |
+
title="VAE CT Slice Generator",
|
| 34 |
+
description=(
|
| 35 |
+
"Upload a **mask** image (grayscale). The model encodes it, decodes to 4 slices (3D CT), "
|
| 36 |
+
f"and returns **slice {OUTPUT_SLICE_INDEX}** as a 2D image for the web."
|
| 37 |
+
),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# --- FastAPI app (Gradio mounted at /) ---
|
| 42 |
+
app = FastAPI(title="VAE CT Slice API")
|
| 43 |
+
|
| 44 |
+
# CORS: allow your website (and others) to call /predict and /generate from the browser
|
| 45 |
+
app.add_middleware(
|
| 46 |
+
CORSMiddleware,
|
| 47 |
+
allow_origins=["*"],
|
| 48 |
+
allow_credentials=True,
|
| 49 |
+
allow_methods=["GET", "POST", "OPTIONS"],
|
| 50 |
+
allow_headers=["*"],
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@app.post("/generate")
|
| 55 |
+
async def generate(file: UploadFile):
|
| 56 |
+
"""Upload mask -> return single slice as data URI (same shape as diffusion /generate)."""
|
| 57 |
+
try:
|
| 58 |
+
raw = await file.read()
|
| 59 |
+
logger.info("[request /generate] INPUT: filename=%s content_type=%s raw_bytes=%s",
|
| 60 |
+
file.filename, file.content_type, len(raw))
|
| 61 |
+
mask = Image.open(io.BytesIO(raw)).convert("L")
|
| 62 |
+
logger.info("[request /generate] image opened: size=%s mode=%s", mask.size, mask.mode)
|
| 63 |
+
png_bytes = inference_to_png(mask, slice_index=OUTPUT_SLICE_INDEX)
|
| 64 |
+
b64 = base64.b64encode(png_bytes).decode("ascii")
|
| 65 |
+
return JSONResponse(content={"image": f"data:image/png;base64,{b64}"})
|
| 66 |
+
except Exception as e:
|
| 67 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@app.post("/predict")
|
| 71 |
+
async def predict(file: UploadFile):
|
| 72 |
+
"""Upload mask -> return single slice as base64 PNG in JSON."""
|
| 73 |
+
try:
|
| 74 |
+
raw = await file.read()
|
| 75 |
+
logger.info("[request /predict] INPUT: filename=%s content_type=%s raw_bytes=%s",
|
| 76 |
+
file.filename, file.content_type, len(raw))
|
| 77 |
+
mask = Image.open(io.BytesIO(raw)).convert("L")
|
| 78 |
+
logger.info("[request /predict] image opened: size=%s mode=%s", mask.size, mask.mode)
|
| 79 |
+
png_bytes = inference_to_png(mask, slice_index=OUTPUT_SLICE_INDEX)
|
| 80 |
+
b64 = base64.b64encode(png_bytes).decode("ascii")
|
| 81 |
+
return JSONResponse(content={"image": b64, "slice_index": OUTPUT_SLICE_INDEX})
|
| 82 |
+
except Exception as e:
|
| 83 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@app.get("/")
|
| 87 |
+
def root():
|
| 88 |
+
return {"status": "ok", "message": "VAE CT slice API. Use /generate or /predict with a mask image."}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
inference.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VAE inference: mask (PIL) -> preprocess -> encode -> decode -> return one slice.
|
| 3 |
+
Input: Single grayscale mask (any size). Preprocess: Grayscale, Resize(256,256), ToTensor [0,1],
|
| 4 |
+
duplicate to 4 slices -> (1, 4, 256, 256) batched format.
|
| 5 |
+
Output: decode(z) shape (1, 4, 256, 256). We return one slice (default index 2) as PNG bytes.
|
| 6 |
+
"""
|
| 7 |
+
import io
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
from typing import Optional, Tuple
|
| 11 |
+
import cv2
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
import torchvision.transforms as T
|
| 17 |
+
from PIL import Image
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
|
| 20 |
+
from model import VAE
|
| 21 |
+
|
| 22 |
+
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO").upper())
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
# --- Config (override via env on Hugging Face) ---
|
| 26 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 27 |
+
MODEL_REPO = os.environ.get("MODEL_REPO", "tan200224/Synthetic-CT-Scan_VAE_Conditional")
|
| 28 |
+
MODEL_FILENAME = os.environ.get("MODEL_FILENAME", "mask2pic_64model_47.pt")
|
| 29 |
+
INPUT_SIZE = 256
|
| 30 |
+
OUTPUT_SLICE_INDEX = 2 # Which of the 4 slices to return (0..3)
|
| 31 |
+
|
| 32 |
+
_model: Optional[nn.Module] = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def load_model(repo_id: str = MODEL_REPO, filename: str = MODEL_FILENAME) -> nn.Module:
|
| 36 |
+
"""Download checkpoint from Hub and load VAE(base=64)."""
|
| 37 |
+
logger.info("[load_model] START repo_id=%s filename=%s device=%s", repo_id, filename, DEVICE)
|
| 38 |
+
path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 39 |
+
size_mb = os.path.getsize(path) / (1024 * 1024) if os.path.exists(path) else 0
|
| 40 |
+
logger.info("[load_model] checkpoint path=%s size=%.1f MB", path, size_mb)
|
| 41 |
+
|
| 42 |
+
model = VAE(base=64).to(DEVICE)
|
| 43 |
+
ckpt = torch.load(path, map_location=DEVICE)
|
| 44 |
+
|
| 45 |
+
if isinstance(ckpt, dict) and "model_state_dict" in ckpt:
|
| 46 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 47 |
+
logger.info("[load_model] load_state_dict from checkpoint['model_state_dict'] OK")
|
| 48 |
+
else:
|
| 49 |
+
model.load_state_dict(ckpt)
|
| 50 |
+
logger.info("[load_model] load_state_dict from raw state_dict OK")
|
| 51 |
+
|
| 52 |
+
model.eval()
|
| 53 |
+
nparams = sum(p.numel() for p in model.parameters())
|
| 54 |
+
logger.info("[load_model] model.eval() set | params=%s | MODEL LOADED SUCCESSFULLY", nparams)
|
| 55 |
+
return model
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_model() -> nn.Module:
|
| 59 |
+
"""Return cached model or load once."""
|
| 60 |
+
global _model
|
| 61 |
+
if _model is None:
|
| 62 |
+
logger.info("[get_model] loading model (first request)")
|
| 63 |
+
_model = load_model()
|
| 64 |
+
return _model
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def preprocess_mask(mask: Image.Image, size: int = INPUT_SIZE) -> torch.Tensor:
|
| 68 |
+
"""
|
| 69 |
+
PIL mask -> (1, 4, size, size) float32 in [0, 1].
|
| 70 |
+
Steps: Grayscale, Resize(size, size), ToTensor, duplicate to 4 channels, add batch dim.
|
| 71 |
+
"""
|
| 72 |
+
logger.info("[preprocess] INPUT size=%s mode=%s", mask.size, mask.mode)
|
| 73 |
+
|
| 74 |
+
transform = T.Compose([
|
| 75 |
+
T.Grayscale(num_output_channels=1),
|
| 76 |
+
T.Resize((size, size), antialias=True),
|
| 77 |
+
T.ToTensor(),
|
| 78 |
+
])
|
| 79 |
+
x = transform(mask) # (1, H, W)
|
| 80 |
+
x_np = x.numpy()
|
| 81 |
+
logger.info("[preprocess] after Grayscale+Resize(%s)+ToTensor shape=%s min=%.4f max=%.4f mean=%.4f",
|
| 82 |
+
(size, size), tuple(x.shape), float(x_np.min()), float(x_np.max()), float(x_np.mean()))
|
| 83 |
+
|
| 84 |
+
x = x.repeat(4, 1, 1) # (4, H, W) - duplicate 1 channel to 4 slices
|
| 85 |
+
x = x.unsqueeze(0) # (1, 4, H, W) - add batch dimension
|
| 86 |
+
logger.info("[preprocess] after duplicate+batch shape=%s", tuple(x.shape))
|
| 87 |
+
return x
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def mask_to_embedding(mask: Image.Image, size: int = INPUT_SIZE) -> torch.Tensor:
|
| 91 |
+
"""Mask -> preprocess -> encode -> z. Uses train() for forward so BatchNorm uses batch stats (batch size 1).
|
| 92 |
+
Returns z = mu (no sampling noise) for most faithful reconstruction."""
|
| 93 |
+
model = get_model()
|
| 94 |
+
x = preprocess_mask(mask, size=size).to(DEVICE)
|
| 95 |
+
model.train()
|
| 96 |
+
try:
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
mu, logvar = model.encode(x)
|
| 99 |
+
z = mu # use mean only for deterministic, most faithful reconstruction (no std*eps)
|
| 100 |
+
finally:
|
| 101 |
+
model.eval()
|
| 102 |
+
return z
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def decode_to_slices(z: torch.Tensor) -> torch.Tensor:
|
| 106 |
+
"""z -> decode -> (1, 4, 256, 256) batched. Uses train() for forward so BatchNorm uses batch stats (batch size 1)."""
|
| 107 |
+
model = get_model()
|
| 108 |
+
model.train()
|
| 109 |
+
try:
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
out = model.decode(z)
|
| 112 |
+
finally:
|
| 113 |
+
model.eval()
|
| 114 |
+
out_np = out.detach().cpu().numpy()
|
| 115 |
+
logger.info("[model output] decode(z) shape=%s min=%.4f max=%.4f mean=%.4f",
|
| 116 |
+
tuple(out.shape), float(out_np.min()), float(out_np.max()), float(out_np.mean()))
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def enhance_slice(slice_2d: np.ndarray,
|
| 121 |
+
contrast: bool = True,
|
| 122 |
+
sharpen: bool = True) -> np.ndarray:
|
| 123 |
+
"""
|
| 124 |
+
Postprocess VAE output slice to reduce blur.
|
| 125 |
+
Input: float32 image [0,1]
|
| 126 |
+
Output: float32 image [0,1]
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
img = slice_2d.astype(np.float32)
|
| 130 |
+
|
| 131 |
+
# --- 1. Contrast stretch (great for CT-like images) ---
|
| 132 |
+
if contrast:
|
| 133 |
+
p2, p98 = np.percentile(img, (2, 98))
|
| 134 |
+
if p98 > p2:
|
| 135 |
+
img = (img - p2) / (p98 - p2)
|
| 136 |
+
img = np.clip(img, 0, 1)
|
| 137 |
+
|
| 138 |
+
# --- 2. Unsharp mask (edge boost) ---
|
| 139 |
+
if sharpen:
|
| 140 |
+
blur = cv2.GaussianBlur(img, (0, 0), sigmaX=1.2)
|
| 141 |
+
img = cv2.addWeighted(img, 1.6, blur, -0.6, 0)
|
| 142 |
+
|
| 143 |
+
return np.clip(img, 0, 1)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def inference(mask: Image.Image, slice_index: int = OUTPUT_SLICE_INDEX) -> Tuple[np.ndarray, torch.Tensor]:
|
| 147 |
+
"""
|
| 148 |
+
Full pipeline: mask -> encode -> decode -> 4 slices.
|
| 149 |
+
Returns (one_slice_2d, full_output_tensor).
|
| 150 |
+
"""
|
| 151 |
+
z = mask_to_embedding(mask)
|
| 152 |
+
out = decode_to_slices(z) # (1, 4, 256, 256) batched
|
| 153 |
+
slice_idx = min(max(0, slice_index), 3)
|
| 154 |
+
one_slice = out[0, slice_idx].detach().cpu().numpy() # (256, 256) float [0,1]
|
| 155 |
+
logger.info("[output slice] slice_index=%s shape=%s min=%.4f max=%.4f",
|
| 156 |
+
slice_idx, one_slice.shape, float(one_slice.min()), float(one_slice.max()))
|
| 157 |
+
return one_slice, out
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def slice_to_png(slice_2d: np.ndarray) -> bytes:
|
| 161 |
+
"""(H, W) float [0,1] -> clip -> scale to uint8 -> PNG bytes."""
|
| 162 |
+
arr = (np.clip(slice_2d, 0.0, 1.0) * 255).astype(np.uint8)
|
| 163 |
+
img = Image.fromarray(arr, mode="L")
|
| 164 |
+
buf = io.BytesIO()
|
| 165 |
+
img.save(buf, format="PNG")
|
| 166 |
+
return buf.getvalue()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def inference_to_png(mask: Image.Image,
|
| 170 |
+
slice_index: int = OUTPUT_SLICE_INDEX,
|
| 171 |
+
contrast: bool = True,
|
| 172 |
+
sharpen: bool = True) -> bytes:
|
| 173 |
+
"""Mask -> inference -> (optional) enhance -> PNG bytes."""
|
| 174 |
+
one_slice, _ = inference(mask, slice_index=slice_index)
|
| 175 |
+
one_slice = enhance_slice(one_slice, contrast=contrast, sharpen=sharpen)
|
| 176 |
+
return slice_to_png(one_slice)
|
| 177 |
+
|
model.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VAE model definition.
|
| 3 |
+
Input: (B, 4, 256, 256) — 4 slices (3D CT label/mask).
|
| 4 |
+
Output: decode(z) -> (B, 4, 256, 256) — 4 reconstructed slices.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Conv(nn.Module):
|
| 11 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.conv = nn.Sequential(
|
| 14 |
+
nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False),
|
| 15 |
+
nn.BatchNorm2d(out_channels),
|
| 16 |
+
nn.LeakyReLU(inplace=True),
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 20 |
+
return self.conv(x)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ConvTranspose(nn.Module):
|
| 24 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.conv = nn.Sequential(
|
| 27 |
+
nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, bias=False),
|
| 28 |
+
nn.BatchNorm2d(out_channels),
|
| 29 |
+
nn.LeakyReLU(inplace=True),
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 33 |
+
return self.conv(x)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class VAE(nn.Module):
|
| 37 |
+
"""VAE: 4-channel input (4 slices) -> latent -> 4-channel output (4 slices)."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, base: int = 64):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.base = base
|
| 42 |
+
|
| 43 |
+
self.encoder = nn.Sequential(
|
| 44 |
+
Conv(4, base, 3, stride=2, padding=1),
|
| 45 |
+
Conv(base, 2 * base, 3, padding=1),
|
| 46 |
+
Conv(2 * base, 2 * base, 3, stride=2, padding=1),
|
| 47 |
+
Conv(2 * base, 2 * base, 3, padding=1),
|
| 48 |
+
Conv(2 * base, 2 * base, 3, stride=2, padding=1),
|
| 49 |
+
Conv(2 * base, 4 * base, 3, padding=1),
|
| 50 |
+
Conv(4 * base, 4 * base, 3, stride=2, padding=1),
|
| 51 |
+
Conv(4 * base, 4 * base, 3, padding=1),
|
| 52 |
+
Conv(4 * base, 4 * base, 3, stride=2, padding=1),
|
| 53 |
+
nn.Conv2d(4 * base, 64 * base, 8),
|
| 54 |
+
nn.LeakyReLU(inplace=True),
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
self.encoder_mu = nn.Conv2d(64 * base, 32 * base, 1)
|
| 58 |
+
self.encoder_logvar = nn.Conv2d(64 * base, 32 * base, 1)
|
| 59 |
+
|
| 60 |
+
self.decoder = nn.Sequential(
|
| 61 |
+
nn.Conv2d(32 * base, 64 * base, 1),
|
| 62 |
+
ConvTranspose(64 * base, 4 * base, 8),
|
| 63 |
+
Conv(4 * base, 4 * base, 3, padding=1),
|
| 64 |
+
ConvTranspose(4 * base, 4 * base, 4, stride=2, padding=1),
|
| 65 |
+
Conv(4 * base, 4 * base, 3, padding=1),
|
| 66 |
+
ConvTranspose(4 * base, 4 * base, 4, stride=2, padding=1),
|
| 67 |
+
Conv(4 * base, 2 * base, 3, padding=1),
|
| 68 |
+
ConvTranspose(2 * base, 2 * base, 4, stride=2, padding=1),
|
| 69 |
+
Conv(2 * base, 2 * base, 3, padding=1),
|
| 70 |
+
ConvTranspose(2 * base, 2 * base, 4, stride=2, padding=1),
|
| 71 |
+
Conv(2 * base, base, 3, padding=1),
|
| 72 |
+
ConvTranspose(base, base, 4, stride=2, padding=1),
|
| 73 |
+
nn.Conv2d(base, 4, 3, padding=1),
|
| 74 |
+
nn.Sigmoid(),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 78 |
+
x = self.encoder(x)
|
| 79 |
+
return self.encoder_mu(x), self.encoder_logvar(x)
|
| 80 |
+
|
| 81 |
+
def reparameterize(self, mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
|
| 82 |
+
"""Standard VAE reparameterization: z = mu + std * eps. For inference (eval mode), return mu for deterministic output."""
|
| 83 |
+
if not self.training:
|
| 84 |
+
return mu
|
| 85 |
+
std = torch.exp(0.5 * logvar)
|
| 86 |
+
eps = torch.randn_like(std)
|
| 87 |
+
return mu + std * eps
|
| 88 |
+
|
| 89 |
+
def decode(self, z: torch.Tensor) -> torch.Tensor:
|
| 90 |
+
return self.decoder(z)
|
| 91 |
+
|
| 92 |
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 93 |
+
mu, logvar = self.encode(x)
|
| 94 |
+
z = self.reparameterize(mu, logvar)
|
| 95 |
+
return self.decode(z), mu, logvar
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
pillow
|
| 4 |
+
numpy
|
| 5 |
+
fastapi
|
| 6 |
+
uvicorn
|
| 7 |
+
gradio>=4.36,<4.44
|
| 8 |
+
gradio_client>=1.2,<1.3
|
| 9 |
+
huggingface_hub>=0.19,<0.26
|
| 10 |
+
opencv-python-headless>=4.8
|