Spaces:
Sleeping
Sleeping
Upload 7 files
Browse files- Dockerfile +29 -0
- fastapi_app/app.py +123 -0
- fastapi_app/requirements.txt +9 -0
- fastapi_app/scripts/data_model.py +19 -0
- fastapi_app/scripts/logging.py +36 -0
- fastapi_app/scripts/utils.py +63 -0
- fastapi_app/templates/index.html +255 -0
Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 6 |
+
build-essential \
|
| 7 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 8 |
+
|
| 9 |
+
COPY fastapi_app/requirements.txt .
|
| 10 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 11 |
+
|
| 12 |
+
# Copy application code (excluding models directory)
|
| 13 |
+
COPY fastapi_app/app.py .
|
| 14 |
+
COPY fastapi_app/scripts ./scripts
|
| 15 |
+
COPY fastapi_app/templates ./templates
|
| 16 |
+
|
| 17 |
+
# Create cache directory for model downloads
|
| 18 |
+
RUN mkdir -p /app/.cache && \
|
| 19 |
+
useradd -m -u 1000 appuser && \
|
| 20 |
+
chown -R appuser:appuser /app
|
| 21 |
+
|
| 22 |
+
USER appuser
|
| 23 |
+
|
| 24 |
+
EXPOSE 8000
|
| 25 |
+
|
| 26 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
|
| 27 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
|
| 28 |
+
|
| 29 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
|
fastapi_app/app.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException, Request
|
| 7 |
+
from fastapi.responses import HTMLResponse
|
| 8 |
+
from fastapi.templating import Jinja2Templates
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from scripts.logging import get_logger
|
| 13 |
+
from scripts.utils import ViTBrainTumorClassifier
|
| 14 |
+
from scripts.data_model import ClassificationResponse, Prediction
|
| 15 |
+
|
| 16 |
+
warnings.filterwarnings("ignore")
|
| 17 |
+
logger = get_logger(__name__)
|
| 18 |
+
|
| 19 |
+
app = FastAPI(
|
| 20 |
+
title="Brain Tumor Classification Inference API",
|
| 21 |
+
description="Vision Transformer based brain tumor classification",
|
| 22 |
+
version="1.0.0"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
BASE_DIR = Path(__file__).parent
|
| 26 |
+
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
| 27 |
+
MODEL = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@app.on_event("startup")
|
| 31 |
+
async def startup_event():
|
| 32 |
+
global MODEL
|
| 33 |
+
try:
|
| 34 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 35 |
+
logger.info(f"Using device: {device}")
|
| 36 |
+
MODEL = ViTBrainTumorClassifier(device=device)
|
| 37 |
+
logger.info("Application startup complete")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Failed to initialize model: {e}")
|
| 40 |
+
raise
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@app.on_event("shutdown")
|
| 44 |
+
async def shutdown_event():
|
| 45 |
+
logger.info("Application shutting down...")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@app.get("/", response_class=HTMLResponse)
|
| 49 |
+
async def index(request: Request):
|
| 50 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@app.get("/health")
|
| 54 |
+
async def health_check():
|
| 55 |
+
return {
|
| 56 |
+
"status": "healthy",
|
| 57 |
+
"model_loaded": MODEL is not None,
|
| 58 |
+
"version": "1.0.0"
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@app.post("/api/v1/classify")
|
| 63 |
+
async def classify_image(file: UploadFile = File(...)) -> ClassificationResponse:
|
| 64 |
+
"""
|
| 65 |
+
Classify a brain tumor from an uploaded image.
|
| 66 |
+
"""
|
| 67 |
+
if MODEL is None:
|
| 68 |
+
raise HTTPException(status_code=500, detail="Model not initialized")
|
| 69 |
+
|
| 70 |
+
allowed_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"}
|
| 71 |
+
file_extension = Path(file.filename).suffix.lower()
|
| 72 |
+
|
| 73 |
+
if file_extension not in allowed_extensions:
|
| 74 |
+
raise HTTPException(
|
| 75 |
+
status_code=400,
|
| 76 |
+
detail=f"Invalid file type. Allowed: {', '.join(allowed_extensions)}"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
contents = await file.read()
|
| 81 |
+
|
| 82 |
+
with tempfile.NamedTemporaryFile(suffix=file_extension, delete=False) as tmp:
|
| 83 |
+
tmp.write(contents)
|
| 84 |
+
tmp_path = tmp.name
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
Image.open(tmp_path).verify()
|
| 88 |
+
except Exception:
|
| 89 |
+
if os.path.exists(tmp_path):
|
| 90 |
+
os.remove(tmp_path)
|
| 91 |
+
raise HTTPException(status_code=400, detail="Invalid image file")
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
logger.info(f"Processing: {file.filename}")
|
| 95 |
+
prediction_result = MODEL.predict(tmp_path)
|
| 96 |
+
|
| 97 |
+
response = ClassificationResponse(
|
| 98 |
+
success=True,
|
| 99 |
+
prediction=Prediction(
|
| 100 |
+
predicted_class=prediction_result["predicted_class"],
|
| 101 |
+
confidence=prediction_result["confidence"],
|
| 102 |
+
all_predictions=prediction_result["all_predictions"]
|
| 103 |
+
),
|
| 104 |
+
message=f"Successfully classified as {prediction_result['predicted_class']}"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
logger.info(f"Complete: {prediction_result['predicted_class']}")
|
| 108 |
+
return response
|
| 109 |
+
|
| 110 |
+
finally:
|
| 111 |
+
if os.path.exists(tmp_path):
|
| 112 |
+
os.remove(tmp_path)
|
| 113 |
+
|
| 114 |
+
except HTTPException:
|
| 115 |
+
raise
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.error(f"Error: {e}")
|
| 118 |
+
raise HTTPException(status_code=500, detail=f"Classification failed: {str(e)}")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
import uvicorn
|
| 123 |
+
uvicorn.run(app="app:app", port=8000, reload=True, host="0.0.0.0")
|
fastapi_app/requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.115.6
|
| 2 |
+
uvicorn[standard]==0.34.0
|
| 3 |
+
jinja2==3.1.5
|
| 4 |
+
python-multipart==0.0.18
|
| 5 |
+
transformers==4.43.3
|
| 6 |
+
torch==2.3.1
|
| 7 |
+
torchvision==0.18.1
|
| 8 |
+
Pillow==10.2.0
|
| 9 |
+
pydantic==2.8.2
|
fastapi_app/scripts/data_model.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field
|
| 2 |
+
from typing import Dict
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Prediction(BaseModel):
|
| 6 |
+
predicted_class: str = Field(..., description="Predicted tumor class")
|
| 7 |
+
confidence: float = Field(..., description="Confidence percentage (0-100)")
|
| 8 |
+
all_predictions: Dict[str, float] = Field(..., description="Confidence scores for all classes")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ClassificationResponse(BaseModel):
|
| 12 |
+
success: bool = Field(..., description="Whether classification was successful")
|
| 13 |
+
prediction: Prediction = Field(..., description="Classification results")
|
| 14 |
+
message: str = Field(default="", description="Additional message or error info")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
fastapi_app/scripts/logging.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import sys
|
| 3 |
+
from logging.handlers import RotatingFileHandler
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def get_logger(name: str) -> logging.Logger:
|
| 8 |
+
logger = logging.getLogger(name)
|
| 9 |
+
|
| 10 |
+
if logger.hasHandlers():
|
| 11 |
+
return logger
|
| 12 |
+
|
| 13 |
+
logger.setLevel(logging.DEBUG)
|
| 14 |
+
logs_dir = Path("logs")
|
| 15 |
+
logs_dir.mkdir(exist_ok=True)
|
| 16 |
+
|
| 17 |
+
formatter = logging.Formatter(
|
| 18 |
+
fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 19 |
+
datefmt="%Y-%m-%d %H:%M:%S"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
console_handler = logging.StreamHandler(sys.stdout)
|
| 23 |
+
console_handler.setLevel(logging.INFO)
|
| 24 |
+
console_handler.setFormatter(formatter)
|
| 25 |
+
logger.addHandler(console_handler)
|
| 26 |
+
|
| 27 |
+
file_handler = RotatingFileHandler(
|
| 28 |
+
logs_dir / "app.log",
|
| 29 |
+
maxBytes=10 * 1024 * 1024,
|
| 30 |
+
backupCount=5
|
| 31 |
+
)
|
| 32 |
+
file_handler.setLevel(logging.DEBUG)
|
| 33 |
+
file_handler.setFormatter(formatter)
|
| 34 |
+
logger.addHandler(file_handler)
|
| 35 |
+
|
| 36 |
+
return logger
|
fastapi_app/scripts/utils.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import ViTImageProcessor, ViTForImageClassification
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import os
|
| 4 |
+
import torch
|
| 5 |
+
from .logging import get_logger
|
| 6 |
+
|
| 7 |
+
logger = get_logger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ViTBrainTumorClassifier:
|
| 11 |
+
CLASS_LABELS = {0: "Glioma", 1: "Meningioma", 2: "No Tumor", 3: "Pituitary"}
|
| 12 |
+
|
| 13 |
+
def __init__(self, device: str = "cpu", model_name: str = "codeby-hp/vit-brain-tumor-classifier"):
|
| 14 |
+
self.device = device
|
| 15 |
+
self.model_name = model_name
|
| 16 |
+
self.model = None
|
| 17 |
+
self.processor = None
|
| 18 |
+
self._load_model()
|
| 19 |
+
|
| 20 |
+
def _load_model(self):
|
| 21 |
+
try:
|
| 22 |
+
logger.info(f"Downloading model from HuggingFace Hub: {self.model_name}")
|
| 23 |
+
|
| 24 |
+
# Download from HuggingFace Hub
|
| 25 |
+
self.processor = ViTImageProcessor.from_pretrained(self.model_name)
|
| 26 |
+
self.model = ViTForImageClassification.from_pretrained(self.model_name)
|
| 27 |
+
self.model.to(self.device)
|
| 28 |
+
self.model.eval()
|
| 29 |
+
|
| 30 |
+
logger.info(f"Model loaded successfully on {self.device}")
|
| 31 |
+
except Exception as e:
|
| 32 |
+
logger.error(f"Model loading failed: {e}")
|
| 33 |
+
raise
|
| 34 |
+
|
| 35 |
+
def predict(self, image_path: str) -> dict:
|
| 36 |
+
try:
|
| 37 |
+
image = Image.open(image_path).convert("RGB")
|
| 38 |
+
inputs = self.processor(images=image, return_tensors="pt")
|
| 39 |
+
inputs = {k: v.to(self.device) for k, v in inputs.items()}
|
| 40 |
+
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
outputs = self.model(**inputs)
|
| 43 |
+
logits = outputs.logits
|
| 44 |
+
|
| 45 |
+
probabilities = torch.nn.functional.softmax(logits, dim=-1)
|
| 46 |
+
predicted_class = torch.argmax(probabilities, dim=-1).item()
|
| 47 |
+
confidence = probabilities[0, predicted_class].item()
|
| 48 |
+
|
| 49 |
+
result = {
|
| 50 |
+
"predicted_class": self.CLASS_LABELS.get(predicted_class, "Unknown"),
|
| 51 |
+
"confidence": round(confidence * 100, 2),
|
| 52 |
+
"all_predictions": {
|
| 53 |
+
self.CLASS_LABELS[i]: round(probabilities[0, i].item() * 100, 2)
|
| 54 |
+
for i in range(len(self.CLASS_LABELS))
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
logger.info(f"Prediction: {result['predicted_class']} ({result['confidence']}%)")
|
| 59 |
+
return result
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
logger.error(f"Prediction error: {e}")
|
| 63 |
+
raise
|
fastapi_app/templates/index.html
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<title>Brain Tumor Classification</title>
|
| 7 |
+
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
| 8 |
+
<style>
|
| 9 |
+
body {
|
| 10 |
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
.glass-effect {
|
| 14 |
+
background: rgba(255, 255, 255, 0.95);
|
| 15 |
+
backdrop-filter: blur(10px);
|
| 16 |
+
border: 1px solid rgba(255, 255, 255, 0.2);
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
.gradient-accent {
|
| 20 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
.spinner {
|
| 24 |
+
display: inline-block;
|
| 25 |
+
width: 20px;
|
| 26 |
+
height: 20px;
|
| 27 |
+
border: 3px solid rgba(255, 255, 255, 0.3);
|
| 28 |
+
border-radius: 50%;
|
| 29 |
+
border-top-color: white;
|
| 30 |
+
animation: spin 0.8s linear infinite;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
.spinner.hidden {
|
| 34 |
+
display: none;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
@keyframes spin {
|
| 38 |
+
to { transform: rotate(360deg); }
|
| 39 |
+
}
|
| 40 |
+
</style>
|
| 41 |
+
</head>
|
| 42 |
+
<body class="bg-gray-50">
|
| 43 |
+
<div class="min-h-screen flex items-center justify-center px-4 py-8">
|
| 44 |
+
<div class="w-full max-w-2xl">
|
| 45 |
+
<!-- Header -->
|
| 46 |
+
<div class="mb-8 text-center">
|
| 47 |
+
<h1 class="text-4xl font-bold text-gray-900 mb-2">Brain Tumor Classification</h1>
|
| 48 |
+
<p class="text-gray-600">Upload an MRI scan for AI-powered analysis</p>
|
| 49 |
+
</div>
|
| 50 |
+
|
| 51 |
+
<!-- Main Card -->
|
| 52 |
+
<div id="mainCard" class="glass-effect rounded-2xl shadow-xl p-8 mb-6">
|
| 53 |
+
<!-- Upload Section -->
|
| 54 |
+
<div id="uploadSection" class="mb-8">
|
| 55 |
+
<label for="imageInput" class="block mb-4">
|
| 56 |
+
<div class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center cursor-pointer hover:border-purple-500 transition-colors">
|
| 57 |
+
<svg class="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
| 58 |
+
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
|
| 59 |
+
</svg>
|
| 60 |
+
<p class="text-gray-700 font-semibold mb-1">Click to upload or drag and drop</p>
|
| 61 |
+
<p class="text-sm text-gray-500">PNG, JPG, GIF up to 10MB</p>
|
| 62 |
+
</div>
|
| 63 |
+
</label>
|
| 64 |
+
<input type="file" id="imageInput" accept="image/*" class="hidden" />
|
| 65 |
+
</div>
|
| 66 |
+
|
| 67 |
+
<!-- Preview Section -->
|
| 68 |
+
<div id="previewSection" class="hidden mb-8">
|
| 69 |
+
<div class="relative rounded-xl overflow-hidden bg-gray-100 mb-4">
|
| 70 |
+
<img id="previewImage" src="" alt="Preview" class="w-full h-auto max-h-96 object-contain" />
|
| 71 |
+
</div>
|
| 72 |
+
<button id="removeButton" class="w-full bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 rounded-lg transition-colors">
|
| 73 |
+
Choose Different Image
|
| 74 |
+
</button>
|
| 75 |
+
</div>
|
| 76 |
+
|
| 77 |
+
<!-- Submit Button -->
|
| 78 |
+
<button id="classifyButton" class="w-full gradient-accent text-white font-semibold py-3 rounded-lg hover:opacity-90 transition-opacity mb-4 flex items-center justify-center gap-2">
|
| 79 |
+
<span id="buttonText">Classify Image</span>
|
| 80 |
+
<span id="spinner" class="hidden spinner"></span>
|
| 81 |
+
</button>
|
| 82 |
+
|
| 83 |
+
<!-- Error Message -->
|
| 84 |
+
<div id="errorMessage" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm"></div>
|
| 85 |
+
</div>
|
| 86 |
+
|
| 87 |
+
<!-- Results Section -->
|
| 88 |
+
<div id="resultsSection" class="hidden glass-effect rounded-2xl shadow-xl p-8">
|
| 89 |
+
<h2 class="text-2xl font-bold text-gray-900 mb-6">Classification Results</h2>
|
| 90 |
+
|
| 91 |
+
<!-- Main Prediction -->
|
| 92 |
+
<div class="mb-8 p-6 gradient-accent text-white rounded-xl">
|
| 93 |
+
<p class="text-sm font-semibold opacity-90 mb-2">DIAGNOSIS</p>
|
| 94 |
+
<p id="mainPrediction" class="text-3xl font-bold mb-2">-</p>
|
| 95 |
+
<p id="mainConfidence" class="text-lg opacity-90">Confidence: -%</p>
|
| 96 |
+
</div>
|
| 97 |
+
|
| 98 |
+
<!-- Detailed Breakdown -->
|
| 99 |
+
<div class="mb-8">
|
| 100 |
+
<h3 class="text-lg font-semibold text-gray-900 mb-4">Confidence Scores</h3>
|
| 101 |
+
<div id="predictionsList" class="space-y-3"></div>
|
| 102 |
+
</div>
|
| 103 |
+
|
| 104 |
+
<!-- Action Buttons -->
|
| 105 |
+
<button id="analyzeButton" class="w-full gradient-accent text-white font-semibold py-3 rounded-lg hover:opacity-90 transition-opacity">
|
| 106 |
+
Analyze Another Image
|
| 107 |
+
</button>
|
| 108 |
+
</div>
|
| 109 |
+
|
| 110 |
+
<!-- Footer -->
|
| 111 |
+
<div class="mt-8 text-center text-gray-600 text-sm">
|
| 112 |
+
<p>Vision Transformer (ViT) powered classification</p>
|
| 113 |
+
</div>
|
| 114 |
+
</div>
|
| 115 |
+
</div>
|
| 116 |
+
|
| 117 |
+
<script>
|
| 118 |
+
const imageInput = document.getElementById('imageInput');
|
| 119 |
+
const uploadSection = document.getElementById('uploadSection');
|
| 120 |
+
const previewSection = document.getElementById('previewSection');
|
| 121 |
+
const previewImage = document.getElementById('previewImage');
|
| 122 |
+
const classifyButton = document.getElementById('classifyButton');
|
| 123 |
+
const removeButton = document.getElementById('removeButton');
|
| 124 |
+
const mainCard = document.getElementById('mainCard');
|
| 125 |
+
const resultsSection = document.getElementById('resultsSection');
|
| 126 |
+
const errorMessage = document.getElementById('errorMessage');
|
| 127 |
+
const analyzeButton = document.getElementById('analyzeButton');
|
| 128 |
+
const mainPrediction = document.getElementById('mainPrediction');
|
| 129 |
+
const mainConfidence = document.getElementById('mainConfidence');
|
| 130 |
+
const predictionsList = document.getElementById('predictionsList');
|
| 131 |
+
const buttonText = document.getElementById('buttonText');
|
| 132 |
+
const spinner = document.getElementById('spinner');
|
| 133 |
+
|
| 134 |
+
imageInput.addEventListener('change', (e) => {
|
| 135 |
+
const file = e.target.files[0];
|
| 136 |
+
if (file) {
|
| 137 |
+
const reader = new FileReader();
|
| 138 |
+
reader.onload = (event) => {
|
| 139 |
+
previewImage.src = event.target.result;
|
| 140 |
+
uploadSection.classList.add('hidden');
|
| 141 |
+
previewSection.classList.remove('hidden');
|
| 142 |
+
resultsSection.classList.add('hidden');
|
| 143 |
+
errorMessage.classList.add('hidden');
|
| 144 |
+
};
|
| 145 |
+
reader.readAsDataURL(file);
|
| 146 |
+
}
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
+
removeButton.addEventListener('click', () => {
|
| 150 |
+
imageInput.value = '';
|
| 151 |
+
previewSection.classList.add('hidden');
|
| 152 |
+
uploadSection.classList.remove('hidden');
|
| 153 |
+
resultsSection.classList.add('hidden');
|
| 154 |
+
errorMessage.classList.add('hidden');
|
| 155 |
+
});
|
| 156 |
+
|
| 157 |
+
classifyButton.addEventListener('click', async () => {
|
| 158 |
+
const file = imageInput.files[0];
|
| 159 |
+
if (!file) {
|
| 160 |
+
showError('Please select an image');
|
| 161 |
+
return;
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
const formData = new FormData();
|
| 165 |
+
formData.append('file', file);
|
| 166 |
+
|
| 167 |
+
classifyButton.disabled = true;
|
| 168 |
+
buttonText.textContent = 'Classifying...';
|
| 169 |
+
spinner.classList.remove('hidden');
|
| 170 |
+
errorMessage.classList.add('hidden');
|
| 171 |
+
|
| 172 |
+
try {
|
| 173 |
+
const response = await fetch('/api/v1/classify', {
|
| 174 |
+
method: 'POST',
|
| 175 |
+
body: formData
|
| 176 |
+
});
|
| 177 |
+
|
| 178 |
+
if (!response.ok) {
|
| 179 |
+
const error = await response.json();
|
| 180 |
+
showError(error.detail || 'Classification failed');
|
| 181 |
+
return;
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
const data = await response.json();
|
| 185 |
+
displayResults(data.prediction);
|
| 186 |
+
} catch (error) {
|
| 187 |
+
showError('Network error: ' + error.message);
|
| 188 |
+
} finally {
|
| 189 |
+
classifyButton.disabled = false;
|
| 190 |
+
buttonText.textContent = 'Classify Image';
|
| 191 |
+
spinner.classList.add('hidden');
|
| 192 |
+
}
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
analyzeButton.addEventListener('click', () => {
|
| 196 |
+
imageInput.value = '';
|
| 197 |
+
previewSection.classList.add('hidden');
|
| 198 |
+
uploadSection.classList.remove('hidden');
|
| 199 |
+
resultsSection.classList.add('hidden');
|
| 200 |
+
mainCard.classList.remove('hidden');
|
| 201 |
+
errorMessage.classList.add('hidden');
|
| 202 |
+
});
|
| 203 |
+
|
| 204 |
+
function displayResults(prediction) {
|
| 205 |
+
mainPrediction.textContent = prediction.predicted_class;
|
| 206 |
+
mainConfidence.textContent = `Confidence: ${prediction.confidence}%`;
|
| 207 |
+
|
| 208 |
+
predictionsList.innerHTML = '';
|
| 209 |
+
Object.entries(prediction.all_predictions).forEach(([className, confidence]) => {
|
| 210 |
+
const progressPercent = Math.round(confidence);
|
| 211 |
+
const barColor = className === prediction.predicted_class ? 'bg-purple-500' : 'bg-gray-300';
|
| 212 |
+
|
| 213 |
+
const html = `
|
| 214 |
+
<div>
|
| 215 |
+
<div class="flex justify-between items-center mb-1">
|
| 216 |
+
<span class="text-gray-700 font-medium">${className}</span>
|
| 217 |
+
<span class="text-gray-600 text-sm">${progressPercent}%</span>
|
| 218 |
+
</div>
|
| 219 |
+
<div class="w-full bg-gray-200 rounded-full h-2">
|
| 220 |
+
<div class="${barColor} h-2 rounded-full transition-all" style="width: ${progressPercent}%"></div>
|
| 221 |
+
</div>
|
| 222 |
+
</div>
|
| 223 |
+
`;
|
| 224 |
+
predictionsList.innerHTML += html;
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
mainCard.classList.add('hidden');
|
| 228 |
+
resultsSection.classList.remove('hidden');
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
function showError(message) {
|
| 232 |
+
errorMessage.textContent = message;
|
| 233 |
+
errorMessage.classList.remove('hidden');
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
const dropZone = document.querySelector('[for="imageInput"]');
|
| 237 |
+
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
|
| 238 |
+
dropZone.addEventListener(eventName, preventDefaults, false);
|
| 239 |
+
});
|
| 240 |
+
|
| 241 |
+
function preventDefaults(e) {
|
| 242 |
+
e.preventDefault();
|
| 243 |
+
e.stopPropagation();
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
dropZone.addEventListener('drop', (e) => {
|
| 247 |
+
const dt = e.dataTransfer;
|
| 248 |
+
const files = dt.files;
|
| 249 |
+
imageInput.files = files;
|
| 250 |
+
const event = new Event('change', { bubbles: true });
|
| 251 |
+
imageInput.dispatchEvent(event);
|
| 252 |
+
});
|
| 253 |
+
</script>
|
| 254 |
+
</body>
|
| 255 |
+
</html>
|