Spaces:
Sleeping
Sleeping
Commit ·
ce4fddb
0
Parent(s):
initial deploy
Browse filesFiles changed (33)
- .gitignoreAdded+50
- DockerfileAdded+17
- README.mdAdded+67
- app/__init__.pyAdded+1
- app/config.pyAdded+66
- app/main.pyAdded+140
- app/models/__init__.pyAdded+1
- app/models/schemas.pyAdded+202
- app/routers/__init__.pyAdded+1
- app/routers/analyze.pyAdded+247
- app/routers/auth.pyAdded+164
- app/routers/chat.pyAdded+78
- app/routers/clinics.pyAdded+174
- app/routers/diet.pyAdded+52
- app/routers/scans.pyAdded+432
- app/routers/stats.pyAdded+46
- app/services/__init__.pyAdded+1
- app/services/auth_service.pyAdded+79
- app/services/chatbot_service.pyAdded+128
- app/services/chest_model.pyAdded+139
- app/services/diet_service.pyAdded+330
- app/services/fracture_classifier.pyAdded+99
- app/services/fracture_model.pyAdded+170
- app/services/image_preprocess.pyAdded+116
- app/services/openrouter_agent.pyAdded+262
- app/services/openrouter_client.pyAdded+58
- app/services/wound_model.pyAdded+127
- app/utils/__init__.pyAdded+1
- app/utils/supabase_client.pyAdded+213
- colab_train_fracture.ipynbAdded+341
- requirements.txtAdded+22
- supabase_schema.sqlAdded+117
- train_fracture_model.pyAdded+247
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Environment variables — NEVER commit these.env.env.local.env.*.local
# Python cache__pycache__/*.py[cod]*$py.class*.pyo*.pyd
# Virtual environmentvenv/.venv/env/ENV/
# Distribution / packagingdist/build/*.egg-info/*.egg.eggs/
# Pytest / coverage.pytest_cache/.coveragehtmlcov/
# Jupyter.ipynb_checkpoints/
# OS.DS_StoreThumbs.db
# IDE.vscode/.idea/*.swp*.swo
# Model weights — large binaries, download at runtime, never commit*.pt*.pth*.bin*.ckpt*.safetensorsmodels/1234567891011121314151617FROM python:3.11-slim
WORKDIR /app
# Install system dependencies for OpenCVRUN apt-get update && apt-get install -y --no-install-recommends \ libgl1-mesa-glx libglib2.0-0 libsm6 libxrender1 libxext6 \ && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 7860
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667---title: XRayVision AI Backendemoji: 🩻colorFrom: bluecolorTo: bluesdk: dockerapp_port: 7860pinned: false---
# XRayVision AI — Backend
Advanced medical diagnostic API using a Hybrid Multi-Model Ensemble.
## Quick Start
```bash# 1. Create virtual environmentpython -m venv venvvenv\Scripts\activate # Windows# source venv/bin/activate # Mac/Linux
# 2. Install dependenciespip install -r requirements.txt
# 3. Copy environment variablescopy .env.example .env# Edit .env with your Supabase, OpenRouter, and Hugging Face keys
# 4. Run the serveruvicorn app.main:app --reload --port 8000```
## API Documentation
Once running, visit:- **Swagger UI**: http://localhost:8000/docs- **ReDoc**: http://localhost:8000/redoc
## Models
| Model | Task | Input | Output ||-------|------|-------|--------|| TorchXRayVision DenseNet121 | Chest Pathology | 224×224 grayscale | 18 pathology probabilities || YOLOv8 | Fracture Localization | Any size RGB | Positive fracture boxes only || HF fracture classifier | Fracture Screening | 224x224 RGB | Image-level fracture/normal probability || Wound-specific HF classifier | Wound Classification | 224×224 RGB | Classification labels || OpenRouter GLM 4.5 Air | Agentic Synthesis | Model outputs + notes | Structured diagnostic report |
Fracture scans use a safer two-stage workflow:- YOLO localizes visible fracture boxes when it can.- The pretrained classifier provides image-level fracture suspicion.- Detector `Not_Fracture` boxes are ignored because they do not prove the whole scan is normal.
## Database Setup
1. Create a Supabase project at https://supabase.com2. Run `supabase_schema.sql` in the SQL Editor3. Create a storage bucket named `xray-images` (private)4. Copy the project URL and keys into `.env`
## Docker Deployment (HF Spaces)
```bashdocker build -t xrayvision-backend .docker run -p 7860:7860 --env-file .env xrayvision-backend```1# XRayVision AI — Backend Application123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Centralized application settings loaded from environment variables."""
from pydantic_settings import BaseSettings, SettingsConfigDictfrom pydantic import Fieldfrom pydantic.aliases import AliasChoicesfrom functools import lru_cacheimport os
class Settings(BaseSettings): # Supabase # Accepts both SUPABASE_KEY and SUPABASE_SERVICE_ROLE_KEY so either # naming convention works in Render / HuggingFace Spaces env vars. supabase_url: str = "https://your-project.supabase.co" supabase_key: str = Field( "your-supabase-service-role-key", validation_alias=AliasChoices("SUPABASE_KEY", "SUPABASE_SERVICE_ROLE_KEY"), ) supabase_anon_key: str = "your-supabase-anon-key"
# OpenRouter openrouter_api_key: str = "" openrouter_model: str = "z-ai/glm-4.5-air:free" openrouter_site_url: str = "http://localhost:5173" openrouter_app_name: str = "XRayVision AI" openrouter_timeout_seconds: float = 60.0
# Hugging Face hf_token: str | None = None
# JWT jwt_secret: str = "change-this-to-a-random-secret-string" jwt_algorithm: str = "HS256" jwt_expiry_hours: int = 24
# Model Config yolo_weights_path: str = "models/fracture_yolov8.pt" allow_generic_yolo_weights: bool = False # Set FRACTURE_CLASSIFIER_ENABLED=false on low-RAM hosts (saves ~400 MB). fracture_classifier_enabled: bool = True fracture_classifier_model_name: str = "prithivMLmods/Bone-Fracture-Detection" wound_model_name: str = "PayamFard123/dermaintel-wound-classifier" confidence_threshold: float = 0.40
# CORS frontend_url: str = "http://localhost:5173"
# Performance — set DISABLE_PRELOAD=true on free-tier hosts (<=512 MB RAM) # to avoid OOM on startup. Models will lazy-load on first use instead. disable_preload: bool = False
model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", extra="ignore", populate_by_name=True, )
@lru_cache()def get_settings() -> Settings: settings = Settings() if settings.hf_token: os.environ.setdefault("HF_TOKEN", settings.hf_token) os.environ.setdefault("HUGGINGFACE_HUB_TOKEN", settings.hf_token) return settings123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""XRayVision AI — FastAPI Application Entry Point.
Initializes the FastAPI app with CORS, model preloading, and all routers."""
from __future__ import annotationsimport loggingimport threadingfrom contextlib import asynccontextmanagerfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.config import get_settings
logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s",)logger = logging.getLogger("xrayvision")
def _preload_models_background(): """Load AI models in a background thread so the server starts immediately.""" logger.info("📦 Preloading AI models in background thread...")
try: from app.services.chest_model import _get_model as load_chest load_chest() logger.info("✅ DenseNet121 (Chest Pathology) loaded") except Exception as e: logger.warning(f"⚠️ DenseNet121 failed to preload: {e}")
try: from app.services.fracture_model import _get_model as load_fracture load_fracture() logger.info("✅ YOLOv8 (Fracture Detection) loaded") except Exception as e: logger.warning(f"⚠️ YOLOv8 failed to preload: {e}")
try: if get_settings().fracture_classifier_enabled: from app.services.fracture_classifier import _get_model as load_fracture_classifier load_fracture_classifier() logger.info("HF Fracture Classifier loaded") except Exception as e: logger.warning(f"HF Fracture Classifier failed to preload: {e}")
try: from app.services.wound_model import _get_model as load_wound load_wound() logger.info("✅ ViT (Wound Classification) loaded") except Exception as e: logger.warning(f"⚠️ ViT failed to preload: {e}")
logger.info("🟢 All AI models loaded and ready!")
@asynccontextmanagerasync def lifespan(app: FastAPI): """Start model loading in background — server is ready immediately.""" logger.info("🚀 XRayVision AI backend starting...")
settings = get_settings() if settings.disable_preload: # On free-tier hosts (<=512 MB RAM) skip preloading entirely. # Models will lazy-load on first use so auth/chat/diet work immediately. logger.info("⏭️ DISABLE_PRELOAD=true — models will load on first use") else: # Full preload on capable hosts (HuggingFace Spaces, Render Standard+) thread = threading.Thread(target=_preload_models_background, daemon=True) thread.start()
logger.info("🟢 XRayVision AI is accepting requests! (models loading in background)") yield logger.info("🔴 XRayVision AI shutting down...")
def create_app() -> FastAPI: """Create and configure the FastAPI application.""" settings = get_settings()
app = FastAPI( title="XRayVision AI", description=( "Advanced medical diagnostic API using a Hybrid Multi-Model Ensemble. " "DenseNet121 for chest pathology, YOLOv8 for fracture detection, " "ViT for wound classification, and OpenRouter GLM 4.5 Air for agentic synthesis." ), version="2.1.0", lifespan=lifespan, docs_url="/docs", redoc_url="/redoc", )
# CORS — allow common dev origins app.add_middleware( CORSMiddleware, allow_origins=[ settings.frontend_url, "http://localhost:5173", "http://localhost:5174", "http://localhost:3000", "http://localhost:3001", "http://localhost:8080", "http://localhost:8081", "http://127.0.0.1:5173", "http://127.0.0.1:3000", ], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
# Register routers from app.routers import auth, analyze, scans, chat, diet, stats, clinics
app.include_router(auth.router) app.include_router(analyze.router) app.include_router(scans.router) app.include_router(chat.router) app.include_router(diet.router) app.include_router(stats.router) app.include_router(clinics.router)
@app.get("/", tags=["health"]) async def health(): return { "status": "healthy", "service": "XRayVision AI", "version": "2.1.0", "models": ["DenseNet121", "YOLOv8", "ViT", "OpenRouter GLM 4.5 Air"], }
@app.get("/health", tags=["health"]) async def health_check(): return {"status": "ok"}
return app
app = create_app()1# Models package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Pydantic schemas for all API request and response models."""
from __future__ import annotationsfrom pydantic import BaseModel, EmailStr, Fieldfrom typing import Optionalfrom datetime import datetime
# ── Auth ──────────────────────────────────────────────────────────────
class RegisterRequest(BaseModel): email: str = Field(..., examples=["alex@hospital.org"]) password: str = Field(..., min_length=8) full_name: str = Field(..., examples=["Dr. Alex Reyes"]) role: str = Field(default="Medical Student")
class LoginRequest(BaseModel): email: str password: str
class AuthResponse(BaseModel): access_token: str token_type: str = "bearer" user: UserProfile
class UserProfile(BaseModel): id: str email: str full_name: str role: str avatar_url: Optional[str] = None settings: dict = {} created_at: Optional[str] = None
class ProfileUpdateRequest(BaseModel): full_name: Optional[str] = None role: Optional[str] = None avatar_url: Optional[str] = None
class SettingsUpdateRequest(BaseModel): settings: dict
# ── Analysis ──────────────────────────────────────────────────────────
class AnalyzeRequest(BaseModel): scan_type: str = Field(..., pattern="^(chest|fracture|wound)$") session_label: Optional[str] = None notes: Optional[str] = None
class BoundingBox(BaseModel): x: float y: float w: float h: float
class Finding(BaseModel): name: str confidence: float severity: str # "critical", "high", "moderate", "low" model: str region: Optional[str] = None icd_code: Optional[str] = None bbox: Optional[BoundingBox] = None color: str = "info" # "destructive", "warning", "info"
class AgentSynthesis(BaseModel): urgency: str # "critical", "high", "medium", "low", "clear" synthesis_text: str recommended_actions: list[str] = [] specialist: Optional[str] = None
class ScanResult(BaseModel): id: str scan_type: str session_label: Optional[str] = None image_url: str urgency: str findings: list[Finding] agent_synthesis: AgentSynthesis model_results: dict = {} created_at: str
class ScanListItem(BaseModel): id: str scan_type: str session_label: Optional[str] = None image_url: str urgency: str findings_count: int created_at: str
class ScanListResponse(BaseModel): scans: list[ScanListItem] total: int
# ── Chat ──────────────────────────────────────────────────────────────
class ChatMessage(BaseModel): role: str # "user" or "assistant" content: str created_at: Optional[str] = None
class ChatRequest(BaseModel): session_id: Optional[str] = None message: str language: str = "en" # "en" or "ur"
class ChatResponse(BaseModel): session_id: str reply: str doctor_type: Optional[str] = None home_remedies: list[str] = []
class ChatSession(BaseModel): id: str title: Optional[str] = None created_at: str
# ── Diet ──────────────────────────────────────────────────────────────
class DietRequest(BaseModel): condition: Optional[str] = None dietary_preferences: str = "balanced" restrictions: list[str] = [] goals: str = "general health" language: str = "en"
class MealItem(BaseModel): name: str description: str calories: Optional[int] = None nutrients: Optional[str] = None
class DayPlan(BaseModel): day: str breakfast: MealItem lunch: MealItem dinner: MealItem snacks: list[MealItem] = []
class DietPlanResponse(BaseModel): title: str summary: str plan: list[DayPlan] tips: list[str] = []
# ── Dashboard Stats ──────────────────────────────────────────────────
class ModelPerformance(BaseModel): name: str task: str auc: float color: str
class DashboardStats(BaseModel): total_scans: int critical_findings: int avg_confidence: float avg_report_time: float recent_scans: list[ScanListItem] finding_distribution: dict[str, int] model_performance: list[ModelPerformance]
# ── Clinic Locator ───────────────────────────────────────────────────
class ClinicResult(BaseModel): name: str type: str address: str lat: float lon: float distance_km: float maps_url: str
class ClinicSearchResponse(BaseModel): clinics: list[ClinicResult] total: int search_location: dict1# Routers package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""Image analysis endpoint: the core AI inference pipeline."""
from __future__ import annotations
import asyncioimport loggingimport uuid
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
from app.config import get_settingsfrom app.models.schemas import AgentSynthesis, BoundingBox, Finding, ScanResultfrom app.services import image_preprocessfrom app.services.auth_service import get_current_user_idfrom app.services.openrouter_agent import synthesize_reportfrom app.utils.supabase_client import insert_scan, upload_image
logger = logging.getLogger(__name__)router = APIRouter(tags=["analyze"])
@router.post("/analyze", response_model=ScanResult)async def analyze_image( file: UploadFile = File(...), scan_type: str = Form(...), session_label: str = Form(default=""), notes: str = Form(default=""), user_id: str = Depends(get_current_user_id),): """Upload an image and run the routed diagnostic ensemble.""" settings = get_settings()
if scan_type not in ("chest", "fracture", "wound"): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="scan_type must be one of: chest, fracture, wound", )
file_bytes = await file.read() if not file_bytes: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Empty file uploaded.")
scan_id = str(uuid.uuid4()) logger.info(f"Starting analysis {scan_id} | type={scan_type} | user={user_id}")
try: raw_findings, model_errors, model_names = await _run_routed_ensemble( file_bytes=file_bytes, scan_type=scan_type, confidence_threshold=settings.confidence_threshold, ) except Exception as exc: logger.error(f"Model inference failed: {exc}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"AI model inference failed: {str(exc)}", ) from exc
try: agent_result = synthesize_report( findings=raw_findings, scan_type=scan_type, patient_notes=notes if notes else None, ) except Exception as exc: logger.error(f"OpenRouter synthesis failed: {exc}") agent_result = { "urgency": "medium", "synthesis_text": "AI synthesis temporarily unavailable. Please review findings manually.", "recommended_actions": ["Consult a radiologist for interpretation"], "specialist": None, }
image_url = "" try: image_url = upload_image(user_id, scan_id, file_bytes, file.content_type or "image/png") except Exception as exc: logger.warning(f"Image upload failed (non-blocking): {exc}")
findings = [ Finding( name=f["name"], confidence=f["confidence"], severity=f["severity"], model=f["model"], region=f.get("region"), icd_code=f.get("icd_code"), bbox=BoundingBox(**f["bbox"]) if f.get("bbox") else None, color=f.get("color", "info"), ) for f in raw_findings ]
synthesis = AgentSynthesis( urgency=agent_result["urgency"], synthesis_text=agent_result["synthesis_text"], recommended_actions=agent_result.get("recommended_actions", []), specialist=agent_result.get("specialist"), )
model_results = { "scan_type": scan_type, "ensemble_mode": "routed", "models_run": model_names, "model_errors": model_errors, "specialist": synthesis.specialist, # persisted here since scans table has no specialist column }
try: scan_record = { "id": scan_id, "user_id": user_id, "scan_type": scan_type, "session_label": session_label or None, "notes": notes or None, "image_url": image_url, "urgency": synthesis.urgency, "findings": [f.model_dump() for f in findings], "agent_synthesis": synthesis.synthesis_text, "agent_actions": synthesis.recommended_actions, "model_results": model_results, } insert_scan(scan_record) except Exception as exc: logger.warning(f"Database insert failed (non-blocking): {exc}")
result = ScanResult( id=scan_id, scan_type=scan_type, session_label=session_label or None, image_url=image_url, urgency=synthesis.urgency, findings=findings, agent_synthesis=synthesis, model_results=model_results, created_at="just now", )
logger.info(f"Analysis {scan_id} complete | findings={len(findings)} | urgency={synthesis.urgency}") return result
async def _run_routed_ensemble( *, file_bytes: bytes, scan_type: str, confidence_threshold: float,) -> tuple[list[dict], list[dict], list[str]]: """Run applicable models in parallel.
Chest and fracture X-rays run DenseNet121 plus fracture YOLO as a cross-check. External wound photos route to the wound classifier only. """ tasks: list[tuple[str, asyncio.Task[list[dict]]]] = []
# Strict routing — each scan type uses only its relevant model(s) # chest → DenseNet121 only (YOLOv8 on chest produces irrelevant fracture labels) # fracture → YOLOv8 only (DenseNet121 is chest-only; on an extremity X-ray it # emits nonsensical chest pathologies like "Pneumonia") # wound → ViT only # DenseNet121 is multi-label (18 independent sigmoids); on diffuse pathology many # correlated labels cluster near their decision boundary. Raise the bar to 60% and # cap the count so the report surfaces only meaningful findings, not the full list. CHEST_THRESHOLD = max(confidence_threshold, 0.60) # raise bar for chest: 60% # Fracture detection should favor sensitivity: a high threshold can miss # subtle metacarpal/phalangeal fractures. We still filter weak normal-class # boxes inside the YOLO service, but allow lower-confidence fracture boxes # through for radiologist review. FRACTURE_THRESHOLD = min(confidence_threshold, 0.15) MAX_CHEST_FINDINGS = 6
if scan_type == "chest": tasks.append(("DenseNet121", asyncio.create_task( asyncio.to_thread(_run_chest, file_bytes, CHEST_THRESHOLD)))) elif scan_type == "fracture": tasks.append(("YOLOv8-Fracture", asyncio.create_task( asyncio.to_thread(_run_fracture, file_bytes, FRACTURE_THRESHOLD)))) else: # wound tasks.append(("WoundClassifier", asyncio.create_task( asyncio.to_thread(_run_wound, file_bytes, confidence_threshold))))
raw_findings: list[dict] = [] model_errors: list[dict] = [] model_names = [name for name, _ in tasks] results = await asyncio.gather(*(task for _, task in tasks), return_exceptions=True)
for (name, _), result in zip(tasks, results): if isinstance(result, Exception): logger.warning(f"{name} inference failed during ensemble: {result}") model_errors.append({"model": name, "error": str(result)}) continue # Cap the multi-label DenseNet output so a wall of near-threshold # chest pathologies doesn't bury the clinically relevant findings. if name == "DenseNet121": result = sorted(result, key=lambda f: f.get("confidence", 0), reverse=True)[:MAX_CHEST_FINDINGS] raw_findings.extend(result)
if not raw_findings and model_errors: error_text = "; ".join(f"{e['model']}: {e['error']}" for e in model_errors) raise RuntimeError(error_text)
raw_findings.sort(key=lambda f: f.get("confidence", 0), reverse=True) return raw_findings, model_errors, model_names
def _run_chest(file_bytes: bytes, confidence_threshold: float) -> list[dict]: from app.services.chest_model import predict_chest_pathologies
preprocessed = image_preprocess.preprocess_for_chest(file_bytes) return predict_chest_pathologies(preprocessed, confidence_threshold)
def _run_fracture(file_bytes: bytes, confidence_threshold: float) -> list[dict]: from app.services.fracture_model import predict_fractures
findings: list[dict] = []
yolo_image = image_preprocess.preprocess_for_yolo(file_bytes) yolo_findings = predict_fractures(yolo_image, confidence_threshold) yolo_positive = [ finding for finding in yolo_findings if finding.get("name") != "No fracture box localized" ] findings.extend(yolo_positive)
if get_settings().fracture_classifier_enabled: try: from app.services.fracture_classifier import predict_fracture_presence
classifier_image = image_preprocess.preprocess_for_vit(file_bytes) classifier_findings = predict_fracture_presence(classifier_image) findings.extend(classifier_findings) except Exception as exc: logger.warning(f"Fracture classifier failed: {exc}")
if findings: findings.sort(key=lambda finding: finding.get("confidence", 0), reverse=True) return findings
return yolo_findings
def _run_wound(file_bytes: bytes, confidence_threshold: float) -> list[dict]: from app.services.wound_model import predict_wound
preprocessed = image_preprocess.preprocess_for_vit(file_bytes) return predict_wound(preprocessed, confidence_threshold)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164"""Authentication endpoints — register, login, get current user."""
from __future__ import annotationsfrom fastapi import APIRouter, HTTPException, status, Dependsfrom app.models.schemas import ( AuthResponse, LoginRequest, ProfileUpdateRequest, RegisterRequest, SettingsUpdateRequest, UserProfile,)from app.services.auth_service import hash_password, verify_password, create_access_token, get_current_user_id, get_current_userfrom app.utils.supabase_client import get_anon_client, get_profile, insert_profile, update_profile
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/register", response_model=AuthResponse)async def register(req: RegisterRequest): """Register a new user account.""" client = get_anon_client()
try: # Create user in Supabase Auth auth_response = client.auth.sign_up({ "email": req.email, "password": req.password, })
if not auth_response.user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Registration failed. Email may already be in use.", )
user_id = auth_response.user.id
# Create profile record manually in the backend insert_profile(user_id, req.full_name, req.role) # Generate JWT token = create_access_token(user_id, req.email)
return AuthResponse( access_token=token, user=UserProfile( id=user_id, email=req.email, full_name=req.full_name, role=req.role, ), )
except HTTPException: raise except Exception as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Registration failed: {str(e)}", )
@router.post("/login", response_model=AuthResponse)async def login(req: LoginRequest): """Sign in with email and password.""" client = get_anon_client()
try: auth_response = client.auth.sign_in_with_password({ "email": req.email, "password": req.password, })
if not auth_response.user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid email or password.", )
user_id = auth_response.user.id
# Fetch profile profile = get_profile(user_id)
# Generate JWT token = create_access_token(user_id, req.email)
return AuthResponse( access_token=token, user=UserProfile( id=user_id, email=req.email, full_name=profile.get("full_name", "User") if profile else "User", role=profile.get("role", "Medical Student") if profile else "Medical Student", avatar_url=profile.get("avatar_url") if profile else None, settings=profile.get("settings", {}) if profile else {}, created_at=profile.get("created_at") if profile else None, ), )
except HTTPException: raise except Exception as e: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Login failed: {str(e)}", )
@router.get("/me", response_model=UserProfile)async def get_me(current_user: dict = Depends(get_current_user)): """Get current authenticated user's profile.""" profile = get_profile(current_user["id"]) if not profile: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Profile not found.", )
return UserProfile( id=profile["id"], email=current_user["email"], # email comes from JWT, not profiles table full_name=profile.get("full_name", "User"), role=profile.get("role", "Medical Student"), avatar_url=profile.get("avatar_url"), settings=profile.get("settings", {}), created_at=profile.get("created_at"), )
@router.patch("/profile", response_model=UserProfile)async def update_me(req: ProfileUpdateRequest, current_user: dict = Depends(get_current_user)): """Update current authenticated user's profile.""" updates = req.model_dump(exclude_unset=True, exclude_none=True) profile = update_profile(current_user["id"], updates) if updates else get_profile(current_user["id"]) if not profile: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Profile not found.") return UserProfile( id=profile["id"], email=current_user["email"], full_name=profile.get("full_name", "User"), role=profile.get("role", "Medical Student"), avatar_url=profile.get("avatar_url"), settings=profile.get("settings", {}), created_at=profile.get("created_at"), )
@router.patch("/settings", response_model=UserProfile)async def update_settings(req: SettingsUpdateRequest, current_user: dict = Depends(get_current_user)): """Persist current user's UI/analysis settings.""" profile = update_profile(current_user["id"], {"settings": req.settings}) if not profile: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Profile not found.") return UserProfile( id=profile["id"], email=current_user["email"], full_name=profile.get("full_name", "User"), role=profile.get("role", "Medical Student"), avatar_url=profile.get("avatar_url"), settings=profile.get("settings", {}), created_at=profile.get("created_at"), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Health chatbot endpoints — FYP requirement."""
from __future__ import annotationsfrom fastapi import APIRouter, Depends, HTTPException, statusfrom app.models.schemas import ChatRequest, ChatResponse, ChatSessionfrom app.services.auth_service import get_current_user_idfrom app.services.chatbot_service import chat_with_health_botfrom app.utils.supabase_client import ( create_chat_session, get_chat_sessions, get_chat_messages, insert_chat_message, user_owns_chat_session,)
router = APIRouter(prefix="/chat", tags=["chat"])
@router.post("", response_model=ChatResponse)async def send_message( req: ChatRequest, user_id: str = Depends(get_current_user_id),): """Send a message to the health chatbot.""" # Create or use existing session session_id = req.session_id if not session_id: session = create_chat_session(user_id, title=req.message[:50]) session_id = session["id"] elif not user_owns_chat_session(session_id, user_id): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Chat session not found.")
# Get conversation history for context history = get_chat_messages(session_id, user_id)
# Save user message insert_chat_message(session_id, "user", req.message)
# Get AI response result = chat_with_health_bot( message=req.message, conversation_history=history, language=req.language, )
# Save assistant response insert_chat_message(session_id, "assistant", result["reply"])
return ChatResponse( session_id=session_id, reply=result["reply"], doctor_type=result.get("doctor_type"), home_remedies=result.get("home_remedies", []), )
@router.get("/sessions", response_model=list[ChatSession])async def list_sessions(user_id: str = Depends(get_current_user_id)): """List all chat sessions for the user.""" sessions = get_chat_sessions(user_id) return [ ChatSession( id=s["id"], title=s.get("title", "Chat"), created_at=s.get("created_at", ""), ) for s in sessions ]
@router.get("/sessions/{session_id}/messages")async def get_messages( session_id: str, user_id: str = Depends(get_current_user_id),): """Get all messages in a chat session.""" messages = get_chat_messages(session_id, user_id) return messages123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Nearby clinic/hospital locator using OpenStreetMap Overpass API."""
from __future__ import annotations
import loggingimport mathfrom typing import Any
import httpxfrom fastapi import APIRouter, Depends, HTTPException, Query
from app.models.schemas import ClinicResult, ClinicSearchResponsefrom app.services.auth_service import get_current_user_id
logger = logging.getLogger(__name__)router = APIRouter(tags=["clinics"])
OVERPASS_ENDPOINTS = ( "https://overpass-api.de/api/interpreter", "https://overpass.kumi.systems/api/interpreter", "https://z.overpass-api.de/api/interpreter",)
AMENITY_LABELS = { "hospital": "Hospital", "clinic": "Clinic", "doctors": "Doctors", "doctor": "Doctors", "pharmacy": "Pharmacy", "health_centre": "Health Centre", "centre": "Health Centre",}
def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """Return distance in km between two GPS coordinates.""" radius = 6371.0 dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1) a = ( math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2 ) return radius * 2 * math.asin(math.sqrt(a))
@router.get("/clinics", response_model=ClinicSearchResponse)async def find_nearby_clinics( lat: float = Query(..., ge=-90, le=90, description="Latitude"), lon: float = Query(..., ge=-180, le=180, description="Longitude"), radius_km: float = Query(default=5.0, ge=0.5, le=25.0, description="Search radius in km"), _user_id: str = Depends(get_current_user_id),): """Find hospitals, clinics, doctors, and pharmacies near the given GPS coordinates.""" radius_m = int(radius_km * 1000) elements = await _fetch_overpass_elements(lat, lon, radius_m) clinics = _parse_clinics(elements, lat, lon, radius_km)
return ClinicSearchResponse( clinics=clinics, total=len(clinics), search_location={"lat": lat, "lon": lon, "radius_km": radius_km}, )
async def _fetch_overpass_elements(lat: float, lon: float, radius_m: int) -> list[dict[str, Any]]: query = f"""[out:json][timeout:25];( node["amenity"~"^(hospital|clinic|doctors|pharmacy|health_centre)$"](around:{radius_m},{lat},{lon}); way["amenity"~"^(hospital|clinic|doctors|pharmacy|health_centre)$"](around:{radius_m},{lat},{lon}); relation["amenity"~"^(hospital|clinic|doctors|pharmacy|health_centre)$"](around:{radius_m},{lat},{lon}); node["healthcare"~"^(hospital|clinic|doctor|pharmacy|centre|health_centre)$"](around:{radius_m},{lat},{lon}); way["healthcare"~"^(hospital|clinic|doctor|pharmacy|centre|health_centre)$"](around:{radius_m},{lat},{lon}); relation["healthcare"~"^(hospital|clinic|doctor|pharmacy|centre|health_centre)$"](around:{radius_m},{lat},{lon}););out center 80;"""
last_error: str | None = None async with httpx.AsyncClient( timeout=httpx.Timeout(30.0, connect=10.0), headers={"User-Agent": "XRayVisionAI/2.1 educational clinic locator"}, follow_redirects=True, ) as client: for endpoint in OVERPASS_ENDPOINTS: try: response = await client.post(endpoint, data={"data": query}) response.raise_for_status() payload = response.json() return payload.get("elements", []) except (httpx.TimeoutException, httpx.HTTPStatusError, httpx.TransportError, ValueError) as exc: last_error = str(exc) logger.warning("Overpass endpoint failed (%s): %s", endpoint, exc)
raise HTTPException( status_code=503, detail=f"Clinic lookup service temporarily unavailable. Tried {len(OVERPASS_ENDPOINTS)} OpenStreetMap mirrors.", ) from RuntimeError(last_error or "Overpass unavailable")
def _parse_clinics(elements: list[dict[str, Any]], lat: float, lon: float, radius_km: float) -> list[ClinicResult]: clinics: list[ClinicResult] = [] seen: set[tuple[str, float, float]] = set()
for element in elements: tags = element.get("tags") or {} name = tags.get("name") or tags.get("operator") or tags.get("brand") or "Unnamed Facility" raw_type = (tags.get("amenity") or tags.get("healthcare") or "clinic").replace(" ", "_").lower() facility_type = AMENITY_LABELS.get(raw_type, raw_type.replace("_", " ").title())
coords = _element_coords(element, lat, lon) if coords is None: continue clat, clon = coords distance = round(_haversine(lat, lon, clat, clon), 2) if distance > radius_km + 0.2: continue
dedupe_key = (name.strip().lower(), round(clat, 4), round(clon, 4)) if dedupe_key in seen: continue seen.add(dedupe_key)
clinics.append( ClinicResult( name=name, type=facility_type, address=_address_from_tags(tags), lat=clat, lon=clon, distance_km=distance, maps_url=f"https://www.google.com/maps/search/?api=1&query={clat},{clon}", ) )
clinics.sort(key=lambda clinic: (clinic.distance_km, clinic.type, clinic.name)) return clinics[:80]
def _element_coords(element: dict[str, Any], fallback_lat: float, fallback_lon: float) -> tuple[float, float] | None: if element.get("type") == "node" and "lat" in element and "lon" in element: return float(element["lat"]), float(element["lon"])
center = element.get("center") or {} if "lat" in center and "lon" in center: return float(center["lat"]), float(center["lon"])
if "bounds" in element: bounds = element["bounds"] try: return ( (float(bounds["minlat"]) + float(bounds["maxlat"])) / 2, (float(bounds["minlon"]) + float(bounds["maxlon"])) / 2, ) except (KeyError, TypeError, ValueError): pass
return fallback_lat, fallback_lon
def _address_from_tags(tags: dict[str, Any]) -> str: parts = [ tags.get("addr:housenumber"), tags.get("addr:street"), tags.get("addr:barangay"), tags.get("addr:suburb"), tags.get("addr:city") or tags.get("addr:municipality"), tags.get("addr:province") or tags.get("addr:state"), tags.get("addr:country"), ] return ", ".join(str(part) for part in parts if part) or "Address not available"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Diet plan generator endpoint — FYP requirement."""
from __future__ import annotationsfrom fastapi import APIRouter, Dependsfrom app.models.schemas import DietRequest, DietPlanResponse, DayPlan, MealItemfrom app.services.auth_service import get_current_user_idfrom app.services.diet_service import generate_diet_plan
router = APIRouter(prefix="/diet", tags=["diet"])
@router.post("", response_model=DietPlanResponse)async def create_diet_plan( req: DietRequest, user_id: str = Depends(get_current_user_id),): """Generate a personalized diet plan based on medical conditions and preferences.""" result = generate_diet_plan( condition=req.condition, dietary_preferences=req.dietary_preferences, restrictions=req.restrictions, goals=req.goals, language=req.language, )
# Parse plan items plan = [] for day_data in result.get("plan", []): def parse_meal(m: dict) -> MealItem: return MealItem( name=m.get("name", "Meal"), description=m.get("description", ""), calories=m.get("calories"), nutrients=m.get("nutrients"), )
snacks = [parse_meal(s) for s in day_data.get("snacks", [])]
plan.append(DayPlan( day=day_data.get("day", "Day"), breakfast=parse_meal(day_data.get("breakfast", {})), lunch=parse_meal(day_data.get("lunch", {})), dinner=parse_meal(day_data.get("dinner", {})), snacks=snacks, ))
return DietPlanResponse( title=result.get("title", "Your Diet Plan"), summary=result.get("summary", ""), plan=plan, tips=result.get("tips", []), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432"""Scan history CRUD endpoints."""
from __future__ import annotationsfrom io import BytesIOfrom fastapi import APIRouter, Depends, HTTPException, status, Queryfrom fastapi.responses import Responsefrom app.models.schemas import ScanResult, ScanListItem, ScanListResponse, Finding, AgentSynthesis, BoundingBoxfrom app.services.auth_service import get_current_user_idfrom app.utils.supabase_client import get_user_scans, get_scan_by_id, delete_scan
router = APIRouter(prefix="/scans", tags=["scans"])
@router.get("", response_model=ScanListResponse)async def list_scans( scan_type: str | None = Query(default=None), limit: int = Query(default=50, le=100), offset: int = Query(default=0, ge=0), user_id: str = Depends(get_current_user_id),): """List all scans for the authenticated user.""" scans, total = get_user_scans(user_id, scan_type=scan_type, limit=limit, offset=offset)
items = [] for s in scans: findings = s.get("findings", []) items.append(ScanListItem( id=s["id"], scan_type=s["scan_type"], session_label=s.get("session_label"), image_url=s.get("image_url", ""), urgency=s.get("urgency", "clear"), findings_count=len(findings) if isinstance(findings, list) else 0, created_at=s.get("created_at", ""), ))
return ScanListResponse(scans=items, total=total)
@router.get("/{scan_id}", response_model=ScanResult)async def get_scan( scan_id: str, user_id: str = Depends(get_current_user_id),): """Get a single scan with full results.""" scan = get_scan_by_id(scan_id, user_id) if not scan: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Scan not found.", )
# Parse findings raw_findings = scan.get("findings", []) findings = [] for f in raw_findings: bbox = None if f.get("bbox"): bbox = BoundingBox(**f["bbox"]) findings.append(Finding( name=f.get("name", "Unknown"), confidence=f.get("confidence", 0), severity=f.get("severity", "low"), model=f.get("model", "Unknown"), region=f.get("region"), icd_code=f.get("icd_code"), bbox=bbox, color=f.get("color", "info"), ))
# Parse agent synthesis; specialist is stored in model_results. agent_actions = scan.get("agent_actions", []) raw_model_results = scan.get("model_results") or {} specialist = raw_model_results.get("specialist") if isinstance(raw_model_results, dict) else None synthesis = AgentSynthesis( urgency=scan.get("urgency", "clear"), synthesis_text=scan.get("agent_synthesis", ""), recommended_actions=agent_actions if isinstance(agent_actions, list) else [], specialist=specialist, )
return ScanResult( id=scan["id"], scan_type=scan["scan_type"], session_label=scan.get("session_label"), image_url=scan.get("image_url", ""), urgency=scan.get("urgency", "clear"), findings=findings, agent_synthesis=synthesis, model_results=scan.get("model_results", {}), created_at=scan.get("created_at", ""), )
@router.delete("/{scan_id}")async def remove_scan( scan_id: str, user_id: str = Depends(get_current_user_id),): """Delete a scan.""" deleted = delete_scan(scan_id, user_id) if not deleted: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Scan not found or already deleted.", ) return {"message": "Scan deleted successfully."}
@router.get("/{scan_id}/export.json")async def export_scan_json( scan_id: str, user_id: str = Depends(get_current_user_id),): """Export a scan report as JSON.""" scan = get_scan_by_id(scan_id, user_id) if not scan: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Scan not found.") return scan
@router.get("/{scan_id}/report.pdf")async def export_scan_pdf( scan_id: str, user_id: str = Depends(get_current_user_id),): """Export a scan report as a PDF.""" scan = get_scan_by_id(scan_id, user_id) if not scan: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Scan not found.")
try: pdf_bytes = _build_scan_pdf(scan) except Exception as exc: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"PDF generation failed: {str(exc)}", ) from exc
filename = f"xrayvision-report-{scan_id}.pdf" return Response( content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="{filename}"'}, )
def _build_scan_pdf(scan: dict) -> bytes: from xml.sax.saxutils import escape from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm from reportlab.lib.enums import TA_CENTER, TA_LEFT from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle, HRFlowable from reportlab.pdfgen import canvas as pdfcanvas
PAGE_W, PAGE_H = A4 BRAND_DARK = colors.HexColor("#0f172a") BRAND_CYAN = colors.HexColor("#0284c7") BRAND_TEAL = colors.HexColor("#0891b2") BRAND_LIGHT = colors.HexColor("#e2e8f0") TEXT = colors.HexColor("#111827") MUTED = colors.HexColor("#64748b") PANEL = colors.HexColor("#f8fafc") SEV_HIGH = colors.HexColor("#dc2626") SEV_MED = colors.HexColor("#d97706") SEV_LOW = colors.HexColor("#2563eb") SEV_CLEAR = colors.HexColor("#059669")
urgency_color_map = { "critical": SEV_HIGH, "high": SEV_HIGH, "medium": SEV_MED, "low": SEV_LOW, "clear": SEV_CLEAR, } sev_color_map = { "critical": SEV_HIGH, "high": SEV_HIGH, "moderate": SEV_MED, "low": SEV_LOW, "clear": SEV_CLEAR, }
def text(value, fallback="-"): if value is None or value == "": return fallback return escape(str(value))
def upper(value, fallback="-"): return text(value, fallback).upper()
def pct(value): try: return f"{float(value):.1f}%" except (TypeError, ValueError): return "-"
def hex_color(color): return color.hexval()[2:]
buffer = BytesIO()
def _on_page(canv: pdfcanvas.Canvas, doc): canv.saveState() try: canv.setFillAlpha(0.055) except Exception: pass canv.setFont("Helvetica-Bold", 44) canv.setFillColor(colors.HexColor("#64748b")) canv.translate(PAGE_W / 2, PAGE_H / 2) canv.rotate(35) canv.drawCentredString(0, 0, "EDUCATIONAL USE ONLY") canv.restoreState()
canv.saveState() canv.setFillColor(BRAND_DARK) canv.rect(0, PAGE_H - 20 * mm, PAGE_W, 20 * mm, fill=1, stroke=0) canv.setFillColor(BRAND_TEAL) canv.rect(0, PAGE_H - 20 * mm, PAGE_W, 1.2 * mm, fill=1, stroke=0) canv.setFont("Helvetica-Bold", 14) canv.setFillColor(colors.white) canv.drawString(16 * mm, PAGE_H - 10.5 * mm, "XRayVision AI") canv.setFont("Helvetica", 8) canv.setFillColor(colors.HexColor("#cbd5e1")) canv.drawString(16 * mm, PAGE_H - 15.4 * mm, "AI-assisted radiology report | Educational platform") canv.setFont("Helvetica-Bold", 7) canv.setFillColor(colors.white) canv.drawRightString(PAGE_W - 16 * mm, PAGE_H - 10.2 * mm, "DIAGNOSTIC REPORT") canv.setFont("Helvetica", 7) canv.setFillColor(colors.HexColor("#cbd5e1")) canv.drawRightString(PAGE_W - 16 * mm, PAGE_H - 15.2 * mm, f"Scan ID: {str(scan.get('id', ''))[:12].upper()}")
canv.setFillColor(BRAND_DARK) canv.rect(0, 0, PAGE_W, 12 * mm, fill=1, stroke=0) canv.setFont("Helvetica", 7) canv.setFillColor(colors.HexColor("#94a3b8")) canv.drawString(16 * mm, 4.3 * mm, "AI-generated educational output. Not a medical device or clinical diagnosis.") canv.setFillColor(colors.white) canv.drawRightString(PAGE_W - 16 * mm, 4.3 * mm, f"Page {doc.page}") canv.restoreState()
doc = SimpleDocTemplate( buffer, pagesize=A4, leftMargin=16 * mm, rightMargin=16 * mm, topMargin=27 * mm, bottomMargin=18 * mm, title=f"XRayVision AI Report - {scan.get('id', '')}", author="XRayVision AI v2.1", subject="AI Diagnostic Report", creator="XRayVision AI - Educational Platform", )
base = getSampleStyleSheet()
def st(name, parent="Normal", **kw): return ParagraphStyle(name, parent=base[parent], **kw)
S = { "title": st("title", "Title", fontName="Helvetica-Bold", fontSize=18, leading=22, textColor=BRAND_DARK, alignment=TA_LEFT, spaceAfter=3), "subtitle": st("sub", "Normal", fontSize=8.5, textColor=MUTED, leading=11, spaceAfter=8), "section": st("section", "Heading2", fontName="Helvetica-Bold", fontSize=11.5, textColor=BRAND_DARK, spaceBefore=12, spaceAfter=5), "body": st("body", "Normal", fontSize=8.4, textColor=TEXT, leading=12.5), "body_small": st("bodySmall", "Normal", fontSize=7.7, textColor=TEXT, leading=10.5), "label": st("label", "Normal", fontName="Helvetica-Bold", fontSize=7.2, textColor=MUTED, leading=9), "mono": st("mono", "Normal", fontSize=7.2, textColor=colors.HexColor("#334155"), fontName="Courier", leading=9.4), "disc": st("disc", "Normal", fontSize=7.2, textColor=colors.HexColor("#64748b"), leading=10, spaceAfter=4), "num": st("num", "Normal", fontName="Helvetica-Bold", fontSize=8, textColor=colors.white, alignment=TA_CENTER, leading=10), }
story = [] findings = scan.get("findings") or [] urgency = str(scan.get("urgency", "clear") or "clear").lower() urg_color = urgency_color_map.get(urgency, SEV_LOW) created_at = str(scan.get("created_at", ""))[:19].replace("T", " ") specialist = (scan.get("model_results") or {}).get("specialist") scan_type = str(scan.get("scan_type", "-") or "-").upper()
story.append(Paragraph("Diagnostic Report", S["title"])) story.append(Paragraph(f"Generated by XRayVision AI multi-model workflow | {text(created_at)}", S["subtitle"])) story.append(HRFlowable(width="100%", thickness=1.2, color=BRAND_TEAL, spaceAfter=8))
summary_data = [[ Paragraph("URGENCY", S["label"]), Paragraph("SCAN TYPE", S["label"]), Paragraph("FINDINGS", S["label"]), Paragraph("GENERATED", S["label"]), ], [ Paragraph(f'<font color="#{hex_color(urg_color)}"><b>{upper(urgency)}</b></font>', S["body"]), Paragraph(text(scan_type), S["body"]), Paragraph(str(len(findings)), S["body"]), Paragraph(text(created_at), S["body_small"]), ]] story.append(Table(summary_data, colWidths=[38 * mm, 37 * mm, 30 * mm, 72 * mm], style=TableStyle([ ("BACKGROUND", (0, 0), (-1, -1), PANEL), ("BOX", (0, 0), (-1, -1), 0.6, BRAND_LIGHT), ("LINEABOVE", (0, 0), (-1, 0), 2.0, urg_color), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("TOPPADDING", (0, 0), (-1, -1), 6), ("BOTTOMPADDING", (0, 0), (-1, -1), 6), ("LEFTPADDING", (0, 0), (-1, -1), 8), ("RIGHTPADDING", (0, 0), (-1, -1), 8), ]))) story.append(Spacer(1, 8))
meta = [ [Paragraph("Scan ID", S["label"]), Paragraph(text(scan.get("id")), S["mono"])], [Paragraph("Session", S["label"]), Paragraph(text(scan.get("session_label")), S["body"])], [Paragraph("Patient Notes", S["label"]), Paragraph(text(scan.get("notes")), S["body"])], ] story.append(Table(meta, colWidths=[34 * mm, 143 * mm], style=TableStyle([ ("BACKGROUND", (0, 0), (0, -1), PANEL), ("BACKGROUND", (1, 0), (1, -1), colors.white), ("GRID", (0, 0), (-1, -1), 0.35, BRAND_LIGHT), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("TOPPADDING", (0, 0), (-1, -1), 4), ("BOTTOMPADDING", (0, 0), (-1, -1), 4), ("LEFTPADDING", (0, 0), (-1, -1), 6), ("RIGHTPADDING", (0, 0), (-1, -1), 6), ]))) story.append(Spacer(1, 10))
story.append(Paragraph("AI Model Findings", S["section"])) story.append(HRFlowable(width="100%", thickness=0.5, color=BRAND_LIGHT, spaceAfter=6))
rows = [[ Paragraph("<b>MODEL</b>", S["mono"]), Paragraph("<b>FINDING</b>", S["mono"]), Paragraph("<b>CONF.</b>", S["mono"]), Paragraph("<b>SEVERITY</b>", S["mono"]), Paragraph("<b>REGION</b>", S["mono"]), Paragraph("<b>ICD-10</b>", S["mono"]), ]] row_styles = [ ("BACKGROUND", (0, 0), (-1, 0), BRAND_DARK), ("TEXTCOLOR", (0, 0), (-1, 0), colors.white), ("GRID", (0, 0), (-1, -1), 0.3, BRAND_LIGHT), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("TOPPADDING", (0, 0), (-1, -1), 5), ("BOTTOMPADDING", (0, 0), (-1, -1), 5), ("LEFTPADDING", (0, 0), (-1, -1), 5), ("RIGHTPADDING", (0, 0), (-1, -1), 5), ]
if not findings: rows.append([ Paragraph("-", S["mono"]), Paragraph("No high-confidence findings reported.", S["body"]), Paragraph("-", S["mono"]), Paragraph("-", S["mono"]), Paragraph("-", S["mono"]), Paragraph("-", S["mono"]), ]) else: for i, finding in enumerate(findings): sev = str(finding.get("severity", "low") or "low").lower() sev_color = sev_color_map.get(sev, SEV_LOW) rows.append([ Paragraph(text(finding.get("model")), S["mono"]), Paragraph(f"<b>{text(finding.get('name'))}</b>", S["body"]), Paragraph(pct(finding.get("confidence")), S["mono"]), Paragraph(f'<font color="#{hex_color(sev_color)}"><b>{upper(sev)}</b></font>', S["body_small"]), Paragraph(text(finding.get("region")), S["body_small"]), Paragraph(text(finding.get("icd_code")), S["mono"]), ]) bg = colors.HexColor("#f9fafb") if i % 2 == 0 else colors.white row_styles.append(("BACKGROUND", (0, i + 1), (-1, i + 1), bg))
story.append(Table(rows, colWidths=[24 * mm, 58 * mm, 18 * mm, 24 * mm, 34 * mm, 19 * mm], style=TableStyle(row_styles), repeatRows=1)) story.append(Spacer(1, 10))
synthesis = scan.get("agent_synthesis") or "No synthesis available." story.append(Paragraph("AI Agent Synthesis", S["section"])) story.append(HRFlowable(width="100%", thickness=0.5, color=BRAND_LIGHT, spaceAfter=6)) story.append(Table([[Paragraph(text(synthesis), S["body"])]], colWidths=[177 * mm], style=TableStyle([ ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#f0f9ff")), ("BOX", (0, 0), (-1, -1), 0.7, colors.HexColor("#7dd3fc")), ("LEFTPADDING", (0, 0), (-1, -1), 8), ("RIGHTPADDING", (0, 0), (-1, -1), 8), ("TOPPADDING", (0, 0), (-1, -1), 8), ("BOTTOMPADDING", (0, 0), (-1, -1), 8), ]))) story.append(Spacer(1, 8))
actions = scan.get("agent_actions") or [] if actions: story.append(Paragraph("Recommended Actions", S["section"])) story.append(HRFlowable(width="100%", thickness=0.5, color=BRAND_LIGHT, spaceAfter=6)) action_rows = [[Paragraph(f"<b>{i + 1}</b>", S["num"]), Paragraph(text(action), S["body"])] for i, action in enumerate(actions)] story.append(Table(action_rows, colWidths=[9 * mm, 168 * mm], style=TableStyle([ ("VALIGN", (0, 0), (-1, -1), "TOP"), ("BACKGROUND", (0, 0), (0, -1), BRAND_CYAN), ("BOX", (0, 0), (-1, -1), 0.3, BRAND_LIGHT), ("INNERGRID", (0, 0), (-1, -1), 0.3, BRAND_LIGHT), ("TOPPADDING", (0, 0), (-1, -1), 5), ("BOTTOMPADDING", (0, 0), (-1, -1), 5), ("LEFTPADDING", (0, 0), (-1, -1), 6), ("RIGHTPADDING", (0, 0), (-1, -1), 6), ]))) story.append(Spacer(1, 6))
if specialist: story.append(Table([[Paragraph("Recommended Specialist", S["label"]), Paragraph(f"<b>{text(specialist)}</b>", S["body"])]], colWidths=[48 * mm, 129 * mm], style=TableStyle([ ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#ecfeff")), ("BOX", (0, 0), (-1, -1), 0.6, colors.HexColor("#67e8f9")), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("TOPPADDING", (0, 0), (-1, -1), 7), ("BOTTOMPADDING", (0, 0), (-1, -1), 7), ("LEFTPADDING", (0, 0), (-1, -1), 8), ("RIGHTPADDING", (0, 0), (-1, -1), 8), ])))
story.append(Spacer(1, 12)) story.append(HRFlowable(width="100%", thickness=0.5, color=BRAND_LIGHT, spaceAfter=6)) story.append(Paragraph( "<b>DISCLAIMER:</b> This report is produced by XRayVision AI, an educational AI diagnostic tool. " "It is NOT a substitute for evaluation by a licensed radiologist or qualified medical professional. " "All findings are AI-estimated probabilities and must be correlated with clinical history. " "In case of emergency, contact your local medical services immediately.", S["disc"], )) story.append(Paragraph( "XRayVision AI | FYP - Minhaj University Lahore | BSSE 8th Semester | May 2026", ParagraphStyle("brand", parent=S["disc"], alignment=TA_CENTER, textColor=colors.HexColor("#9ca3af")), ))
doc.build(story, onFirstPage=_on_page, onLaterPages=_on_page) return buffer.getvalue()12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Dashboard statistics endpoint."""
from __future__ import annotationsfrom fastapi import APIRouter, Dependsfrom app.models.schemas import DashboardStats, ScanListItem, ModelPerformancefrom app.services.auth_service import get_current_user_idfrom app.utils.supabase_client import get_user_stats, get_user_scans
router = APIRouter(tags=["stats"])
@router.get("/stats", response_model=DashboardStats)async def dashboard_stats(user_id: str = Depends(get_current_user_id)): """Get aggregated dashboard statistics for the current user.""" stats = get_user_stats(user_id) recent_raw, _ = get_user_scans(user_id, limit=5)
recent = [ ScanListItem( id=s["id"], scan_type=s["scan_type"], session_label=s.get("session_label"), image_url=s.get("image_url", ""), urgency=s.get("urgency", "clear"), findings_count=len(s.get("findings", [])), created_at=s.get("created_at", ""), ) for s in recent_raw ]
# Static model performance (from benchmarks) model_perf = [ ModelPerformance(name="DenseNet121", task="Chest Pathology", auc=0.847, color="bg-primary"), ModelPerformance(name="YOLOv8", task="Fracture Detection", auc=0.891, color="bg-secondary"), ModelPerformance(name="ViT", task="Wound Classification", auc=0.823, color="bg-info"), ]
return DashboardStats( total_scans=stats["total_scans"], critical_findings=stats["critical_findings"], avg_confidence=stats["avg_confidence"], avg_report_time=8.4, # Estimated average recent_scans=recent, finding_distribution=stats["finding_distribution"], model_performance=model_perf, )1# Services package12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""JWT authentication and password hashing service."""
from __future__ import annotationsfrom datetime import datetime, timedelta, timezonefrom jose import JWTError, jwtfrom passlib.context import CryptContextfrom fastapi import HTTPException, status, Dependsfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentialsfrom app.config import get_settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")security = HTTPBearer()
def hash_password(password: str) -> str: """Hash a plain-text password using bcrypt.""" return pwd_context.hash(password)
def verify_password(plain: str, hashed: str) -> bool: """Verify a plain-text password against its hash.""" return pwd_context.verify(plain, hashed)
def create_access_token(user_id: str, email: str) -> str: """Create a JWT access token.""" settings = get_settings() expire = datetime.now(timezone.utc) + timedelta(hours=settings.jwt_expiry_hours) payload = { "sub": user_id, "email": email, "exp": expire, "iat": datetime.now(timezone.utc), } return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
def decode_token(token: str) -> dict: """Decode and validate a JWT token.""" settings = get_settings() try: payload = jwt.decode( token, settings.jwt_secret, algorithms=[settings.jwt_algorithm] ) return payload except JWTError as e: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Invalid or expired token: {str(e)}", headers={"WWW-Authenticate": "Bearer"}, )
def get_current_user_id( credentials: HTTPAuthorizationCredentials = Depends(security),) -> str: """FastAPI dependency — extract user_id from the Authorization header.""" payload = decode_token(credentials.credentials) user_id = payload.get("sub") if not user_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing user identifier.", ) return user_id
def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security),) -> dict: """FastAPI dependency — extract user_id and email from the JWT.""" payload = decode_token(credentials.credentials) user_id = payload.get("sub") if not user_id: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token missing user identifier.", ) return {"id": user_id, "email": payload.get("email", "")}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Health chatbot service powered by OpenRouter GLM 4.5 Air.
FYP requirement: General doctor bot for health queries, symptom analysis,home remedies, doctor type recommendation, and multilingual support."""
from __future__ import annotationsimport loggingfrom app.services.openrouter_client import complete_text
logger = logging.getLogger(__name__)
SYSTEM_PROMPT_EN = """You are XRayVision AI Health Assistant — a knowledgeable, empathetic medical chatbot.You help patients with:1. Symptom analysis and possible conditions2. Basic home remedies and first-aid guidance3. Doctor type recommendations (which specialist to see)4. General health and disease information5. When to seek emergency medical care
IMPORTANT RULES:- Always remind users that you are an AI assistant, not a real doctor.- For serious symptoms, ALWAYS recommend visiting a hospital.- Be empathetic and clear in your responses.- If asked about medications, suggest consulting a pharmacist or doctor.- Provide evidence-based information when possible.- Keep responses concise but thorough (2-4 paragraphs max).
Respond in a structured, helpful manner. If you recommend a doctor type, mention it clearly.If you suggest home remedies, list them as bullet points."""
SYSTEM_PROMPT_UR = """آپ XRayVision AI ہیلتھ اسسٹنٹ ہیں — ایک ذہین اور ہمدرد طبی چیٹ بوٹ۔آپ مریضوں کی مدد کرتے ہیں:1. علامات کا تجزیہ اور ممکنہ بیماریاں2. بنیادی گھریلو علاج اور فرسٹ ایڈ3. ڈاکٹر کی سفارش (کس ماہر سے ملیں)4. عام صحت اور بیماریوں کی معلومات5. کب ایمرجنسی میں جانا چاہیے
اہم قواعد:- ہمیشہ یاد دلائیں کہ آپ AI اسسٹنٹ ہیں، حقیقی ڈاکٹر نہیں۔- سنگین علامات کے لیے ہمیشہ ہسپتال جانے کی سفارش کریں۔- اردو میں جواب دیں۔"""
def chat_with_health_bot( message: str, conversation_history: list[dict] | None = None, language: str = "en",) -> dict: """Process a health query and return AI response.
Args: message: The user's message. conversation_history: Previous messages for context. language: "en" for English, "ur" for Urdu.
Returns: Dict with reply, doctor_type, and home_remedies. """ system_prompt = SYSTEM_PROMPT_UR if language == "ur" else SYSTEM_PROMPT_EN
# Build conversation context messages = [system_prompt]
if conversation_history: for msg in conversation_history[-10:]: # Last 10 messages for context role = "User" if msg.get("role") == "user" else "Assistant" messages.append(f"{role}: {msg.get('content', '')}")
messages.append(f"User: {message}")
lang_instruction = "" if language == "ur": lang_instruction = "\n\nIMPORTANT: Respond entirely in Urdu (اردو)."
full_prompt = "\n\n".join(messages) + lang_instruction + """
Respond with helpful medical guidance. Also include at the end of your response (in a new line):DOCTOR_TYPE: <specialist type or "none">HOME_REMEDIES: <comma-separated list of remedies or "none">"""
try: response_text = complete_text(full_prompt, temperature=0.35, max_tokens=1200) return _parse_chat_response(response_text) except Exception as e: logger.error(f"Chatbot error: {e}") return { "reply": ( "I apologize, but I'm currently unable to process your request. " "Please try again later or consult a medical professional directly." if language == "en" else "معذرت، میں ابھی آپ کی درخواست پر عمل نہیں کر سکتا۔ " "براہ کرم بعد میں دوبارہ کوشش کریں یا براہ راست ڈاکٹر سے مشورہ کریں۔" ), "doctor_type": None, "home_remedies": [], }
def _parse_chat_response(text: str) -> dict: """Parse the chat response to extract doctor type and remedies.""" lines = text.strip().split("\n") reply_lines = [] doctor_type = None home_remedies = []
for line in lines: stripped = line.strip() if stripped.upper().startswith("DOCTOR_TYPE:"): val = stripped.split(":", 1)[1].strip() doctor_type = val if val.lower() != "none" else None elif stripped.upper().startswith("HOME_REMEDIES:"): val = stripped.split(":", 1)[1].strip() if val.lower() != "none": home_remedies = [r.strip() for r in val.split(",") if r.strip()] else: reply_lines.append(line)
return { "reply": "\n".join(reply_lines).strip(), "doctor_type": doctor_type, "home_remedies": home_remedies, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Chest pathology detection using TorchXRayVision DenseNet121.
This model is pretrained on 700K+ clinical X-ray images and outputsprobabilities for 18 different chest pathologies."""
from __future__ import annotationsimport numpy as npimport torchimport logging
logger = logging.getLogger(__name__)
# Lazy-loaded model singleton_model = None_pathology_names: list[str] = []
def _get_model(): """Load the DenseNet121 model (lazy singleton).""" global _model, _pathology_names if _model is None: logger.info("Loading TorchXRayVision DenseNet121 model...") try: import torchxrayvision as xrv _model = xrv.models.DenseNet(weights="densenet121-res224-all") _model.eval() _pathology_names = list(_model.pathologies) logger.info(f"DenseNet121 loaded. Pathologies: {_pathology_names}") except Exception as e: logger.error(f"Failed to load DenseNet121: {e}") raise return _model
def predict_chest_pathologies(preprocessed_image: np.ndarray, confidence_threshold: float = 0.40) -> list[dict]: """Run chest pathology inference.
Args: preprocessed_image: numpy array of shape (1, 1, 224, 224) normalized to [-1024, 1024] range. confidence_threshold: minimum probability to include in results.
Returns: List of findings, each with name, confidence, severity, model, region. """ model = _get_model()
with torch.no_grad(): tensor_input = torch.from_numpy(preprocessed_image).float() outputs = model(tensor_input) probabilities = outputs.cpu().numpy()[0]
findings = [] for i, (name, prob) in enumerate(zip(_pathology_names, probabilities)): confidence = float(prob) * 100 # Convert to percentage
if confidence < confidence_threshold * 100: continue
# Determine severity based on confidence if confidence >= 80: severity = "high" color = "destructive" elif confidence >= 60: severity = "moderate" color = "warning" else: severity = "low" color = "info"
# Map pathology to anatomical region region = _get_region(name) icd_code = _get_icd_code(name)
findings.append({ "name": name, "confidence": round(confidence, 1), "severity": severity, "model": "DenseNet121", "region": region, "icd_code": icd_code, "color": color, })
# Sort by confidence descending findings.sort(key=lambda x: x["confidence"], reverse=True) return findings
def _get_region(pathology: str) -> str: """Map pathology name to anatomical region.""" region_map = { "Atelectasis": "Lung parenchyma", "Cardiomegaly": "Mediastinum", "Consolidation": "Lung parenchyma", "Edema": "Bilateral", "Effusion": "Pleural space", "Emphysema": "Lung parenchyma", "Fibrosis": "Lung parenchyma", "Hernia": "Diaphragm", "Infiltration": "Lung parenchyma", "Mass": "Lung parenchyma", "Nodule": "Lung parenchyma", "Pleural_Thickening": "Pleural space", "Pneumonia": "Lung parenchyma", "Pneumothorax": "Pleural space", "Enlarged Cardiomediastinum": "Mediastinum", "Lung Opacity": "Lung parenchyma", "Lung Lesion": "Lung parenchyma", "Fracture": "Rib cage", } return region_map.get(pathology, "Chest")
def _get_icd_code(pathology: str) -> str: """Map pathology name to ICD-10 code.""" icd_map = { "Atelectasis": "J98.1", "Cardiomegaly": "I51.7", "Consolidation": "J18.9", "Edema": "J81", "Effusion": "J90", "Emphysema": "J43.9", "Fibrosis": "J84.1", "Hernia": "K44.9", "Infiltration": "R91.8", "Mass": "R91.1", "Nodule": "R91.1", "Pleural_Thickening": "J92.9", "Pneumonia": "J18.9", "Pneumothorax": "J93.9", "Enlarged Cardiomediastinum": "R93.1", "Lung Opacity": "R91.8", "Lung Lesion": "R91.1", "Fracture": "S22.9", } return icd_map.get(pathology, "R93.1")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Personalized diet plan generator powered by OpenRouter.
The model creates the menu, while this service adds condition-specificguardrails and validates that the response is complete enough to show."""
from __future__ import annotations
import jsonimport loggingimport re
from app.services.openrouter_client import complete_text
logger = logging.getLogger(__name__)
HYPERTENSION_TERMS = ("hypertension", "high blood pressure", "blood pressure", "bp")DIABETES_TERMS = ("diabetes", "diabetic", "blood sugar", "glucose")KIDNEY_TERMS = ("kidney", "renal", "ckd", "dialysis")
def generate_diet_plan( condition: str | None = None, dietary_preferences: str = "balanced", restrictions: list[str] | None = None, goals: str = "general health", language: str = "en",) -> dict: """Generate a personalized weekly diet plan.""" restrictions = restrictions or [] condition_text = condition or "general wellness" restrictions_text = ", ".join(restrictions) if restrictions else "none" lang_instruction = "Respond entirely in Urdu." if language == "ur" else ""
prompt = f"""You are a nutrition assistant creating an educational 7-day meal plan.
PATIENT CONTEXT:- Medical Condition: {condition_text}- Dietary Preference: {dietary_preferences}- Restrictions: {restrictions_text}- Health Goals: {goals}
{lang_instruction}
MEDICAL AND SAFETY RULES:{_condition_rules(condition_text, goals)}
RESTRICTION RULES:{_restriction_rules(restrictions)}
QUALITY RULES:- Include exactly 7 days, Day 1 through Day 7.- Use realistic meals and portions, not extreme dieting.- Calorie values must be plausible estimates per meal.- Do not include foods that violate allergies or restrictions.- Tips must include one professional-safety note when a medical condition is present.- Do not claim the plan diagnoses, treats, cures, or replaces clinician care.
Respond ONLY in this JSON format, with no markdown or extra text:{{ "title": "<diet plan title>", "summary": "<2-3 sentence summary of the diet approach>", "plan": [ {{ "day": "Day 1", "breakfast": {{"name": "<meal>", "description": "<brief description>", "calories": <number>, "nutrients": "<key nutrients>"}}, "lunch": {{"name": "<meal>", "description": "<brief description>", "calories": <number>, "nutrients": "<key nutrients>"}}, "dinner": {{"name": "<meal>", "description": "<brief description>", "calories": <number>, "nutrients": "<key nutrients>"}}, "snacks": [{{"name": "<snack>", "description": "<brief>", "calories": <number>, "nutrients": "<key nutrients>"}}] }} ], "tips": ["<health tip 1>", "<health tip 2>", "<health tip 3>"]}}"""
try: response_text = complete_text(prompt, temperature=0.25, max_tokens=2600) parsed = _parse_diet_response(response_text) return _normalize_diet_plan(parsed, condition_text, dietary_preferences, restrictions, goals) except Exception as exc: logger.error("Diet plan generation failed: %s", exc) return _fallback_diet_plan(condition_text, dietary_preferences, restrictions, goals)
def _has_any(text: str, terms: tuple[str, ...]) -> bool: normalized = text.lower() return any(term in normalized for term in terms)
def _condition_rules(condition: str, goals: str) -> str: context = f"{condition} {goals}".lower() rules = [ "Use whole foods, realistic portions, and culturally adaptable meals.", "Avoid claiming the plan treats, cures, or replaces care from a clinician.", "Do not include foods that conflict with stated allergies or restrictions.", "Include calorie estimates, but avoid extreme daily calorie restriction.", ]
if _has_any(context, HYPERTENSION_TERMS): rules.extend([ "For blood pressure, follow a DASH-style pattern: vegetables, fruits, beans/lentils, whole grains, fish/poultry/soy, nuts/seeds, and unsaturated fats.", "Keep sodium low: prefer unsalted/no-salt-added foods; avoid processed meats, instant noodles, pickles, salty sauces, regular miso, regular soy sauce, and salty packaged snacks.", "Mention a sodium target of no more than 2,300 mg/day, and ideally 1,500 mg/day if advised by a clinician.", "Emphasize potassium-rich foods only with a caution: people with kidney disease or potassium-raising medicines should ask a clinician first.", ]) if _has_any(context, DIABETES_TERMS): rules.extend([ "For diabetes, distribute carbohydrates across meals and pair carbs with protein, fiber, or healthy fat.", "Avoid sugary drinks and large dessert portions; prefer low-glycemic whole grains, legumes, non-starchy vegetables, lean proteins, and unsweetened foods.", ]) if _has_any(context, KIDNEY_TERMS): rules.extend([ "For kidney disease, do not recommend high-potassium or high-phosphorus patterns unless clinician-approved.", "Avoid generic advice to increase potassium; recommend renal dietitian review.", ])
return "\n".join(f"- {rule}" for rule in rules)
def _restriction_rules(restrictions: list[str]) -> str: joined = " ".join(restrictions).lower() rules: list[str] = []
if "dairy" in joined or "lactose" in joined: rules.append("Dairy-free means no milk, yogurt, cheese, paneer, butter, cream, whey, casein, or cottage cheese; use fortified unsweetened alternatives if needed.") if "gluten" in joined: rules.append("Gluten-free means no wheat, barley, rye, regular bread, regular pasta, or standard wraps; use certified gluten-free grains.") if "nut" in joined or "peanut" in joined: rules.append("Nut allergy means no tree nuts, peanuts, nut butters, almond milk, cashews, walnuts, pistachios, or nut-based snacks.") if "shellfish" in joined or "shrimp" in joined: rules.append("Shellfish restriction means no shrimp, prawns, crab, lobster, or shellfish sauces.")
return "\n".join(f"- {rule}" for rule in rules) or "- No extra restriction-specific exclusions."
def _parse_diet_response(text: str) -> dict: """Parse the model response into structured diet plan.""" cleaned = text.strip() if cleaned.startswith("```"): lines = cleaned.split("\n") cleaned = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:]).strip()
try: parsed = json.loads(cleaned) except json.JSONDecodeError: logger.warning("Failed to parse diet plan JSON") return {}
return { "title": parsed.get("title", "Your Personalized Diet Plan"), "summary": parsed.get("summary", ""), "plan": parsed.get("plan", []), "tips": parsed.get("tips", []), }
def _normalize_diet_plan( plan: dict, condition: str = "general wellness", dietary_preferences: str = "balanced", restrictions: list[str] | None = None, goals: str = "general health",) -> dict: """Keep generated plans complete and add condition-specific guardrails.""" restrictions = restrictions or [] days = plan.get("plan") if isinstance(plan.get("plan"), list) else [] if len(days) != 7: logger.warning("Diet plan had %s days; using validated fallback", len(days)) return _fallback_diet_plan(condition, dietary_preferences, restrictions, goals)
for idx, day in enumerate(days[:7], start=1): if not isinstance(day, dict): return _fallback_diet_plan(condition, dietary_preferences, restrictions, goals) day["day"] = day.get("day") or f"Day {idx}" for meal_name in ("breakfast", "lunch", "dinner"): meal = day.get(meal_name) if not isinstance(meal, dict) or not meal.get("name"): logger.warning("Diet plan missing %s on day %s; using fallback", meal_name, idx) return _fallback_diet_plan(condition, dietary_preferences, restrictions, goals) if not isinstance(day.get("snacks"), list): day["snacks"] = []
tips = [str(t) for t in plan.get("tips", []) if str(t).strip()] context = f"{condition} {goals}"
if _has_any(context, HYPERTENSION_TERMS): tips = _merge_tips(tips, [ "Keep sodium under 2,300 mg/day; ask a clinician whether a 1,500 mg/day target is appropriate.", "Use potassium-rich foods for blood pressure only if you do not have kidney disease and are not on potassium-raising medicines.", "Choose no-salt-added foods and herbs/spices instead of salty sauces or packaged snacks.", ]) if _has_any(context, DIABETES_TERMS): tips = _merge_tips(tips, [ "Monitor blood glucose response and coordinate meal timing with prescribed diabetes medicines.", "Pair carbohydrate foods with protein, fiber, and healthy fats to reduce glucose spikes.", ]) if _has_any(context, KIDNEY_TERMS): tips = _merge_tips(tips, [ "Kidney disease diets must be individualized for potassium, phosphorus, sodium, protein, and fluid limits.", "Review this plan with a renal dietitian or clinician before following it.", ]) if condition and condition.lower() != "general wellness": tips = _merge_tips(tips, [ "This educational plan should be reviewed by a qualified clinician or dietitian for your diagnosis, medicines, labs, and allergies.", ])
return { "title": plan.get("title") or "Your Personalized Diet Plan", "summary": plan.get("summary") or "A structured 7-day meal plan built around whole foods, balanced portions, and the stated health goals.", "plan": days[:7], "tips": tips[:6], }
def _merge_tips(existing: list[str], required: list[str]) -> list[str]: merged = list(existing) comparable = " ".join(_tip_key(tip) for tip in existing) for tip in required: if _tip_key(tip) not in comparable: merged.append(tip) return merged
def _tip_key(tip: str) -> str: words = re.sub(r"[^a-z0-9]+", " ", tip.lower()).strip().split() return " ".join(words[:5])
def _fallback_diet_plan( condition: str = "general wellness", dietary_preferences: str = "balanced", restrictions: list[str] | None = None, goals: str = "general health",) -> dict: """Return a validated fallback plan when the model is unavailable.""" restrictions = restrictions or [] context = f"{condition} {goals}".lower() restrictions_text = " ".join(restrictions).lower() dairy_free = "dairy" in restrictions_text or "lactose" in restrictions_text vegetarian = "vegetarian" in dietary_preferences.lower() or "vegan" in dietary_preferences.lower()
if _has_any(context, HYPERTENSION_TERMS): protein_lunch = "Lentil Quinoa Bowl" if vegetarian else "Grilled Chicken Brown Rice Bowl" dinner_name = "Bean and Vegetable Stew" if vegetarian else "Herb Baked Fish" dinner_nutrients = "Fiber, magnesium, plant protein" if vegetarian else "Omega-3, protein, potassium" dairy_alt = "fortified unsweetened soy milk" if dairy_free else "low-fat yogurt" return { "title": "7-Day Low-Sodium DASH-Style Diet Plan", "summary": "A blood-pressure-focused plan emphasizing vegetables, fruits, legumes, whole grains, lean proteins, unsalted nuts or seeds, and low-sodium preparation. It avoids salty sauces and highly processed foods while keeping dairy optional based on restrictions.", "plan": [ { "day": f"Day {i}", "breakfast": { "name": "Oat Berry Bowl", "description": f"Rolled oats with berries, chia seeds, cinnamon, and {dairy_alt}", "calories": 360, "nutrients": "Fiber, magnesium, potassium", }, "lunch": { "name": protein_lunch, "description": "Whole grains, vegetables, herbs, olive oil, and no-salt-added protein", "calories": 470, "nutrients": "Protein, fiber, unsaturated fats", }, "dinner": { "name": dinner_name, "description": "Served with sweet potato and steamed greens; seasoned with lemon, garlic, and herbs instead of salt", "calories": 510, "nutrients": dinner_nutrients, }, "snacks": [ { "name": "Fruit with Unsalted Seeds", "description": "Apple or orange with unsalted pumpkin or sunflower seeds", "calories": 180, "nutrients": "Fiber, minerals", } ], } for i in range(1, 8) ], "tips": [ "Keep sodium under 2,300 mg/day; ask a clinician whether a 1,500 mg/day target is appropriate.", "Use no-salt-added foods and herbs/spices instead of salty sauces, pickles, processed meats, or packaged snacks.", "Use potassium-rich foods for blood pressure only if you do not have kidney disease and are not on potassium-raising medicines.", "This educational plan should be reviewed by a qualified clinician or dietitian for your diagnosis, medicines, labs, and allergies.", ], }
return { "title": "General 7-Day Balanced Diet Plan", "summary": "A 7-day balanced diet plan focusing on whole foods, lean proteins, and plenty of vegetables.", "plan": [ { "day": f"Day {i}", "breakfast": { "name": "Oatmeal with Fruit", "description": "Steel-cut oats topped with banana, berries, and cinnamon", "calories": 350, "nutrients": "Fiber, vitamins, magnesium", }, "lunch": { "name": "Protein Salad Bowl", "description": "Mixed greens with lean protein or beans, avocado, and olive oil dressing", "calories": 450, "nutrients": "Protein, healthy fats, fiber", }, "dinner": { "name": "Balanced Grain Plate", "description": "Whole grains with vegetables and fish, poultry, tofu, or legumes", "calories": 500, "nutrients": "Protein, fiber, minerals", }, "snacks": [ { "name": "Fruit or Unsalted Seeds", "description": "A simple whole-food snack", "calories": 180, "nutrients": "Fiber, minerals", } ], } for i in range(1, 8) ], "tips": [ "Stay hydrated with water unless your clinician has given fluid restrictions.", "Eat meals at consistent times and include vegetables at most meals.", "This educational plan should be reviewed by a qualified clinician or dietitian for your diagnosis, medicines, labs, and allergies.", ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Image-level fracture classification using a pretrained HF vision model.
YOLO is kept for localization only. This classifier provides the image-levelsecond opinion, which is safer than treating detector "Not_Fracture" boxes asproof that the whole scan is normal."""
from __future__ import annotations
import loggingfrom PIL import Image
logger = logging.getLogger(__name__)
_processor = None_model = None
def _get_model(): """Load the fracture classifier and processor lazily.""" global _processor, _model if _model is None: logger.info("Loading pretrained fracture classifier...") try: from transformers import AutoImageProcessor, AutoModelForImageClassification from app.config import get_settings
model_name = get_settings().fracture_classifier_model_name try: _processor = AutoImageProcessor.from_pretrained(model_name) except Exception: from transformers import AutoProcessor
_processor = AutoProcessor.from_pretrained(model_name) _model = AutoModelForImageClassification.from_pretrained(model_name) _model.eval() logger.info(f"Fracture classifier loaded: {model_name}") except Exception as exc: logger.error(f"Failed to load fracture classifier: {exc}") raise return _processor, _model
def predict_fracture_presence(image: Image.Image) -> list[dict]: """Classify whether the full image likely contains a fracture.""" import torch
processor, model = _get_model() inputs = processor(images=image.convert("RGB"), return_tensors="pt")
with torch.no_grad(): outputs = model(**inputs) probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]
id2label = model.config.id2label ranked = sorted( ((float(probs[i]) * 100, str(id2label[int(i)])) for i in range(len(probs))), reverse=True, ) top_conf, top_label = ranked[0] top_key = _normalize_label(top_label)
if _is_fracture_label(top_key): if top_conf >= 85: severity, color = "high", "destructive" elif top_conf >= 65: severity, color = "moderate", "warning" else: severity, color = "low", "info"
return [{ "name": "Fracture suspected", "confidence": round(top_conf, 1), "severity": severity, "model": "FractureClassifier", "region": "Full image", "icd_code": "S02-S92", "color": color, }]
return [{ "name": "No fracture suspected by classifier", "confidence": round(top_conf, 1), "severity": "clear", "model": "FractureClassifier", "region": "Full image", "icd_code": "", "color": "success", }]
def _normalize_label(label: str) -> str: return label.lower().replace("-", "_").replace(" ", "_")
def _is_fracture_label(label: str) -> bool: if any(token in label for token in ("not", "normal", "negative", "no_fracture", "nofracture")): return False return "fracture" in label or "fractured" in label or label in {"positive", "label_1", "1"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Bone fracture detection using YOLOv8.
Uses the Ultralytics YOLOv8 model for real-time object detectionand localization of fractures in X-ray images."""
from __future__ import annotationsfrom pathlib import Pathimport numpy as npimport logging
logger = logging.getLogger(__name__)
# Lazy-loaded model singleton_model = None
def _get_model(): """Load the YOLOv8 model (lazy singleton).""" global _model if _model is None: logger.info("Loading YOLOv8 model...") try: from ultralytics import YOLO from app.config import get_settings
settings = get_settings() weights = settings.yolo_weights_path weights_name = Path(weights).name.lower() generic_weights = {"yolov8n.pt", "yolov8s.pt", "yolov8m.pt", "yolov8l.pt", "yolov8x.pt"} if weights_name in generic_weights and not settings.allow_generic_yolo_weights: raise RuntimeError( "Generic YOLO weights are not valid for medical fracture delivery. " "Set YOLO_WEIGHTS_PATH to fracture-trained weights, or set " "ALLOW_GENERIC_YOLO_WEIGHTS=true only for demo mode." ) if not Path(weights).exists() and weights_name not in generic_weights: raise FileNotFoundError( f"Fracture YOLO weights not found at '{weights}'. " "Place fracture-trained weights there or update YOLO_WEIGHTS_PATH." ) _model = YOLO(weights) logger.info(f"YOLOv8 loaded from: {weights}") except Exception as e: logger.error(f"Failed to load YOLOv8: {e}") raise return _model
def predict_fractures(image: np.ndarray, confidence_threshold: float = 0.15) -> list[dict]: """Run fracture detection inference.
Args: image: BGR numpy array (original size, YOLO handles resizing). confidence_threshold: minimum confidence to include detections.
Returns: List of findings with bounding boxes, confidence, and severity. """ model = _get_model()
results = model(image, conf=confidence_threshold, imgsz=960, verbose=False)
findings = [] img_h, img_w = image.shape[:2]
for result in results: boxes = result.boxes if boxes is None: continue
for box in boxes: # Get bounding box coordinates (xyxy format) x1, y1, x2, y2 = box.xyxy[0].cpu().numpy() conf = float(box.conf[0].cpu().numpy()) cls_id = int(box.cls[0].cpu().numpy()) cls_name = str(result.names.get(cls_id, f"class_{cls_id}")) cls_key = cls_name.lower().replace(" ", "_")
# Convert to percentage-based coordinates for the frontend bbox = { "x": round(float(x1 / img_w * 100), 1), "y": round(float(y1 / img_h * 100), 1), "w": round(float((x2 - x1) / img_w * 100), 1), "h": round(float((y2 - y1) / img_h * 100), 1), }
confidence = round(conf * 100, 1)
# Map raw class names to clean medical labels label = _clean_class_name(cls_name)
# Skip very low-confidence "Not_Fracture" detections — not useful to display if cls_key in ("not_fracture", "normal", "negative"): continue
# Determine severity if confidence >= 80: severity = "high" color = "destructive" elif confidence >= 60: severity = "moderate" color = "warning" else: severity = "low" color = "info"
icd = "S02-S92" if cls_key == "fracture" or cls_key.endswith("_fracture") else ""
findings.append({ "name": label, "confidence": confidence, "severity": severity, "model": "YOLOv8", "region": _infer_region(bbox), "icd_code": icd, "bbox": bbox, "color": color, })
# Sort by confidence descending findings.sort(key=lambda x: x["confidence"], reverse=True)
# If no fractures detected, return a "clear" finding if not findings: findings.append({ "name": "No fracture box localized", "confidence": 0.0, "severity": "low", "model": "YOLOv8", "region": "Full image", "icd_code": "", "color": "warning", })
return findings
def _clean_class_name(cls_name: str) -> str: """Map raw Roboflow class names to clean medical labels.""" mapping = { "fracture": "Fracture Detected", "not fracture": "No Fracture Detected", "not_fracture": "No Fracture Detected", "normal": "No Fracture Detected", "negative": "No Fracture Detected", "boneanomaly": "Bone Anomaly", "bonelesion": "Bone Lesion", "foreignbody": "Foreign Body", "metal": "Metallic Implant", "periostealreaction": "Periosteal Reaction", "pronationsign": "Pronation Sign", "softtissue": "Soft Tissue Finding", "hardware": "Surgical Hardware", } return mapping.get(cls_name.lower().replace(" ", "_"), cls_name.replace("_", " ").title())
def _infer_region(bbox: dict) -> str: """Infer the anatomical region based on bounding box position.""" cx = bbox["x"] + bbox["w"] / 2 cy = bbox["y"] + bbox["h"] / 2
if cy < 30: return "Upper extremity" elif cy < 60: return "Mid-body / Torso" else: return "Lower extremity"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Image preprocessing utilities for medical image analysis."""
from __future__ import annotationsimport numpy as npimport cv2from PIL import Imageimport ioimport torch
def load_image_from_bytes(file_bytes: bytes) -> np.ndarray: """Load an image from raw bytes into a numpy array (BGR).
Supports common image formats through OpenCV and DICOM through pydicom. """ nparr = np.frombuffer(file_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if img is not None: return img
return load_dicom_from_bytes(file_bytes)
def load_dicom_from_bytes(file_bytes: bytes) -> np.ndarray: """Decode DICOM pixel data into an 8-bit BGR image.""" try: import pydicom except ImportError as exc: raise ValueError("DICOM support requires pydicom to be installed.") from exc
try: ds = pydicom.dcmread(io.BytesIO(file_bytes), force=True) arr = ds.pixel_array.astype(np.float32) except Exception as exc: raise ValueError("Could not decode the uploaded image or DICOM file.") from exc
slope = float(getattr(ds, "RescaleSlope", 1.0)) intercept = float(getattr(ds, "RescaleIntercept", 0.0)) arr = arr * slope + intercept
photo = str(getattr(ds, "PhotometricInterpretation", "")).upper() if photo == "MONOCHROME1": arr = arr.max() - arr
arr = arr - arr.min() max_val = arr.max() if max_val > 0: arr = arr / max_val img8 = (arr * 255).clip(0, 255).astype(np.uint8) return cv2.cvtColor(img8, cv2.COLOR_GRAY2BGR)
def preprocess_for_chest(file_bytes: bytes) -> np.ndarray: """Preprocess an image for TorchXRayVision DenseNet121.
Returns a normalized 224×224 grayscale image as a numpy array with shape (1, 1, 224, 224) ready for model input. """ img = load_image_from_bytes(file_bytes)
# Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply CLAHE for contrast enhancement (important for X-rays) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) enhanced = clahe.apply(gray)
# Resize to 224x224 resized = cv2.resize(enhanced, (224, 224), interpolation=cv2.INTER_AREA)
# Normalize to [0, 1] then scale to [-1024, 1024] as TorchXRayVision expects normalized = resized.astype(np.float32) # TorchXRayVision expects images in range [-1024, 1024] normalized = (normalized / 255.0) * 2048.0 - 1024.0
# Add batch and channel dimensions: (1, 1, 224, 224) tensor_input = normalized[np.newaxis, np.newaxis, :, :] return tensor_input
def preprocess_for_yolo(file_bytes: bytes) -> np.ndarray: """Preprocess an image for YOLOv8 inference.
Returns the image as a numpy array (BGR) at its original size. YOLO handles its own resizing internally. """ img = load_image_from_bytes(file_bytes)
# Apply CLAHE on grayscale channel for better contrast lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) l_channel, a, b = cv2.split(lab) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) l_enhanced = clahe.apply(l_channel) enhanced = cv2.merge([l_enhanced, a, b]) result = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR)
return result
def preprocess_for_vit(file_bytes: bytes) -> Image.Image: """Preprocess an image for ViT classification.
Returns a PIL Image (RGB) — the ViT processor handles resizing/normalization. """ try: return Image.open(io.BytesIO(file_bytes)).convert("RGB") except Exception: bgr = load_dicom_from_bytes(file_bytes) rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) return Image.fromarray(rgb)
def image_to_base64(file_bytes: bytes) -> str: """Convert image bytes to a base64-encoded string for multimodal APIs.""" import base64 return base64.b64encode(file_bytes).decode("utf-8")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Agentic reasoning engine using OpenRouter GLM 4.5 Air.
Synthesizes outputs from all specialized models into a unified,clinically actionable diagnostic report with urgency classification."""
from __future__ import annotationsimport jsonimport loggingfrom app.services.openrouter_client import complete_text
logger = logging.getLogger(__name__)
def synthesize_report( findings: list[dict], scan_type: str, patient_notes: str | None = None, image_base64: str | None = None,) -> dict: """Generate an agentic synthesis report from model findings.
Args: findings: List of findings from the vision models. scan_type: "chest", "fracture", or "wound". patient_notes: Optional notes from the clinician. image_base64: Optional base64-encoded image for multimodal analysis.
Returns: Dict with urgency, synthesis_text, recommended_actions, specialist. """ prompt = _build_synthesis_prompt(findings, scan_type, patient_notes)
try: response_text = complete_text(prompt, temperature=0.1, max_tokens=1400) parsed = _parse_synthesis_response(response_text)
# Double-check: if any finding has confidence > 70 but urgency is "clear", escalate high_conf_findings = [f for f in findings if f.get("confidence", 0) > 70 and f.get("severity") != "clear"] if high_conf_findings and parsed["urgency"] == "clear": parsed["urgency"] = "medium" parsed["synthesis_text"] += ( " Note: High-confidence findings detected — " "radiologist review is recommended." )
# The LLM doesn't always honor the >70% cardiac rule — validate its choice. parsed["specialist"] = _validate_specialist( parsed.get("specialist"), scan_type, findings )
return parsed
except Exception as e: logger.error(f"OpenRouter synthesis failed: {e}") # Fallback: generate a basic report from findings alone return _fallback_synthesis(findings, scan_type)
def _build_synthesis_prompt( findings: list[dict], scan_type: str, patient_notes: str | None,) -> str: """Construct the structured prompt for the reasoning model."""
findings_text = "\n".join( f" - {f['name']}: {f['confidence']}% confidence, " f"severity={f.get('severity', 'unknown')}, " f"model={f.get('model', 'unknown')}, " f"region={f.get('region', 'unknown')}, " f"ICD-10={f.get('icd_code', 'N/A')}" for f in findings )
notes_section = "" if patient_notes: notes_section = f"\n\nClinical Notes from Referring Physician:\n{patient_notes}"
return f"""You are an expert AI radiology assistant integrated into the XRayVision AI system.You are analyzing the output of specialized medical imaging models.
SCAN TYPE: {scan_type.upper()}
MODEL FINDINGS:{findings_text}{notes_section}
Based on these findings, provide a clinical synthesis report. You MUST respond in the following JSON format ONLY (no markdown, no extra text):
{{ "urgency": "<one of: critical, high, medium, low, clear>", "synthesis_text": "<2-4 sentence clinical interpretation of the findings, written as a radiologist would. Reference specific findings, their clinical significance, and how they relate to each other.>", "recommended_actions": [ "<action 1>", "<action 2>", "<action 3>", "<action 4>" ], "specialist": "<recommended specialist type, e.g., Cardiologist, Orthopedic Surgeon, Pulmonologist, or null if clear>"}}
IMPORTANT RULES:1. Be clinically precise. Reference the TOP 2-3 findings by confidence only. Ignore findings below 55% in your narrative.2. If any finding has severity "high" or confidence > 80%, urgency should be at minimum "high".3. If no significant pathology is detected, set urgency to "clear" and recommend routine follow-up.4. Always include a recommendation to consult a qualified radiologist.5. recommended_actions should be specific, actionable medical steps — max 4 actions.6. For fracture scans: if "Fracture suspected" or "Fracture Detected" is present, do NOT call the scan clear. Explain whether localization came from YOLO boxes or image-level classifier evidence.7. "No fracture box localized" means YOLO did not find a box; it is not proof of no fracture.8. For specialist: choose based ONLY on the highest-confidence finding (>60%). - Lung Opacity / Infiltration / Pneumonia / Atelectasis / Consolidation / Edema → Pulmonologist - Cardiomegaly / Enlarged Cardiomediastinum (only if >70% confidence) → Cardiologist - Fracture / Bone anomaly → Orthopedic Surgeon - Effusion / Pneumothorax → Pulmonologist or Thoracic Surgeon - Wound / Laceration → General Surgeon - If unclear, default to Pulmonologist for chest scans.7. This is for educational use — include appropriate disclaimers in your synthesis."""
def _parse_synthesis_response(response_text: str) -> dict: """Parse the model response into a structured dict.""" text = response_text.strip()
# Remove markdown code fences if present if text.startswith("```"): lines = text.split("\n") text = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:]) text = text.strip()
parsed = _try_json_parse(text) if parsed is None: start = text.find("{") end = text.rfind("}") if start != -1 and end != -1 and end > start: parsed = _try_json_parse(text[start:end + 1])
if isinstance(parsed, str): parsed = _try_json_parse(parsed)
if isinstance(parsed, dict): return { "urgency": parsed.get("urgency", "medium"), "synthesis_text": parsed.get("synthesis_text", ""), "recommended_actions": parsed.get("recommended_actions", []), "specialist": parsed.get("specialist"), }
logger.warning("Failed to parse OpenRouter JSON response, using raw text.") return { "urgency": "medium", "synthesis_text": text[:500], "recommended_actions": [ "Consult a qualified radiologist for definitive interpretation", "Correlate with clinical symptoms and patient history", "Consider additional imaging if findings are inconclusive", ], "specialist": None, }
def _try_json_parse(text: str): try: return json.loads(text) except json.JSONDecodeError: return None
def _fallback_synthesis(findings: list[dict], scan_type: str) -> dict: """Generate a basic synthesis when OpenRouter is unavailable.""" if not findings or all(f.get("severity") == "clear" for f in findings): return { "urgency": "clear", "synthesis_text": ( "No significant pathology detected in the submitted image. " "The AI models did not identify findings exceeding the confidence threshold. " "Routine follow-up is recommended." ), "recommended_actions": [ "No immediate action required", "Continue routine screening schedule", "Consult radiologist if symptoms persist", ], "specialist": None, }
# Sort findings by confidence sorted_findings = sorted(findings, key=lambda f: f.get("confidence", 0), reverse=True) top = sorted_findings[0]
urgency = "high" if top["confidence"] > 70 else "medium" if top["confidence"] > 50 else "low"
names = ", ".join(f["name"] for f in sorted_findings[:3]) synthesis = ( f"AI models detected the following findings: {names}. " f"The highest confidence finding is {top['name']} at {top['confidence']}%. " f"Please consult a qualified radiologist for definitive diagnosis." )
return { "urgency": urgency, "synthesis_text": synthesis, "recommended_actions": [ "Seek radiologist consultation for definitive interpretation", f"Consider {top.get('region', 'targeted')} imaging follow-up", "Correlate with clinical symptoms and patient history", "Do not dismiss findings — clinical verification required", ], "specialist": _suggest_specialist(scan_type, sorted_findings), }
def _validate_specialist( specialist: str | None, scan_type: str, findings: list[dict]) -> str | None: """Override an unjustified specialist recommendation from the LLM.
Cardiologist is only appropriate for a chest scan when a cardiac finding (Cardiomegaly / Enlarged Cardiomediastinum) exceeds 70% confidence — the same rule given in the prompt. The LLM doesn't always follow it, so we fall back to the deterministic suggestion when it doesn't. """ if not specialist: return specialist
if scan_type == "chest" and "cardiolog" in specialist.lower(): cardiac = {"Cardiomegaly", "Enlarged Cardiomediastinum"} has_cardiac = any( f.get("name") in cardiac and f.get("confidence", 0) >= 70 for f in findings ) if not has_cardiac: return _suggest_specialist(scan_type, findings)
return specialist
def _suggest_specialist(scan_type: str, findings: list[dict]) -> str | None: """Suggest a specialist based on the highest-confidence finding.""" if scan_type == "fracture": has_positive = any( "fracture" in f.get("name", "").lower() and "no fracture" not in f.get("name", "").lower() for f in findings ) return "Orthopedic Surgeon" if has_positive else None if scan_type == "wound": return "General Surgeon"
if scan_type == "chest": # Only recommend Cardiologist if cardiac findings are high-confidence cardiac = {"Cardiomegaly", "Enlarged Cardiomediastinum"} for f in findings: if f["name"] in cardiac and f.get("confidence", 0) >= 70: return "Cardiologist" # Default to Pulmonologist for all other chest pathologies return "Pulmonologist"
return None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""OpenRouter chat-completions client."""
from __future__ import annotations
import httpxfrom app.config import get_settings
def complete_text( prompt: str, *, system_prompt: str | None = None, temperature: float = 0.2, max_tokens: int = 2048,) -> str: """Send a prompt to OpenRouter and return the assistant text.""" settings = get_settings() if not settings.openrouter_api_key: raise RuntimeError("OPENROUTER_API_KEY is not configured.")
messages = [] if system_prompt: messages.append({"role": "system", "content": system_prompt}) messages.append({"role": "user", "content": prompt})
response = httpx.post( "https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {settings.openrouter_api_key}", "Content-Type": "application/json", "HTTP-Referer": settings.openrouter_site_url, "X-Title": settings.openrouter_app_name, }, json={ "model": settings.openrouter_model, "messages": messages, "temperature": temperature, "max_tokens": max_tokens, }, timeout=settings.openrouter_timeout_seconds, ) try: response.raise_for_status() except httpx.HTTPStatusError as exc: detail = response.text[:500] raise RuntimeError( f"OpenRouter request failed with HTTP {response.status_code}: {detail}" ) from exc
data = response.json() choices = data.get("choices") or [] if not choices: raise RuntimeError("OpenRouter returned no choices.")
content = choices[0].get("message", {}).get("content", "") if not content: raise RuntimeError("OpenRouter returned an empty response.") return content123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""External wound classification using a wound-specific Hugging Face classifier."""
from __future__ import annotationsfrom PIL import Imageimport logging
logger = logging.getLogger(__name__)
# Lazy-loaded model singletons_processor = None_model = None
def _get_model(): """Load the ViT model and processor (lazy singleton).""" global _processor, _model if _model is None: logger.info("Loading wound classification model...") try: from transformers import AutoImageProcessor, AutoModelForImageClassification from app.config import get_settings
model_name = get_settings().wound_model_name _processor = AutoImageProcessor.from_pretrained(model_name) _model = AutoModelForImageClassification.from_pretrained(model_name) _model.eval() logger.info(f"Wound model loaded successfully: {model_name}") except Exception as e: logger.error(f"Failed to load wound model: {e}") raise return _processor, _model
# dermaintel-wound-classifier classes → clean label + approximate ICD-10 code.# "normal_skin" is the model's negative class; the rest are wound types._WOUND_LABELS: dict[str, tuple[str, str]] = { "pressure_ulcer": ("Pressure Ulcer", "L89.90"), "venous_ulcer": ("Venous Ulcer", "I83.009"), "arterial_ulcer": ("Arterial Ulcer", "I70.25"), "diabetic_ulcer": ("Diabetic Foot Ulcer", "E11.621"), "surgical_wound": ("Surgical Wound", "T81.89XA"), "traumatic_wound": ("Traumatic Wound", "T14.8"), "normal_skin": ("Normal Skin", ""),}
# Secondary wound types below the top prediction are only worth showing if they# carry some real signal — a 7-way softmax baseline is ~14%._SECONDARY_MIN_CONFIDENCE = 15.0
def predict_wound(image: Image.Image, confidence_threshold: float = 0.10) -> list[dict]: """Run wound classification inference.
The underlying model is a 7-class softmax (6 wound types + normal_skin), so we report the top prediction directly rather than thresholding every class — a confident wound call on 7 classes can sit well below 40%.
Args: image: PIL Image (RGB). confidence_threshold: retained for API compatibility; not used to gate the top prediction (softmax always has a most-likely class).
Returns: List of findings with classification labels and confidence. """ import torch
processor, model = _get_model()
inputs = processor(images=image, return_tensors="pt") with torch.no_grad(): outputs = model(**inputs) probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]
id2label = model.config.id2label ranked = sorted( ((float(probs[i]) * 100, id2label[int(i)]) for i in range(len(probs))), reverse=True, )
top_conf, top_label = ranked[0]
# If the model is most confident the skin is normal, say so honestly — # using the model's real confidence, not a fabricated number. if top_label == "normal_skin": return [{ "name": "No significant wound detected", "confidence": round(top_conf, 1), "severity": "clear", "model": "WoundClassifier", "region": "External", "icd_code": "", "color": "success", }]
# Otherwise report the detected wound type(s): always the top prediction, # plus any other wound classes carrying meaningful signal. findings: list[dict] = [] for conf, label in ranked: if label == "normal_skin": continue if findings and conf < _SECONDARY_MIN_CONFIDENCE: break
name, icd = _WOUND_LABELS.get(label, (label.replace("_", " ").title(), "T14.8"))
if conf >= 70: severity, color = "high", "destructive" elif conf >= 40: severity, color = "moderate", "warning" else: severity, color = "low", "info"
findings.append({ "name": name, "confidence": round(conf, 1), "severity": severity, "model": "WoundClassifier", "region": "External", "icd_code": icd, "color": color, }) if len(findings) >= 5: break
return findings1# Utils package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Supabase client for database operations and file storage."""
from __future__ import annotationsfrom supabase import create_client, Clientfrom app.config import get_settingsfrom functools import lru_cache
@lru_cache()def get_supabase_client() -> Client: """Get a cached Supabase client instance.""" settings = get_settings() return create_client(settings.supabase_url, settings.supabase_key)
def get_anon_client() -> Client: """Get a Supabase client with anon key (for auth operations).""" settings = get_settings() return create_client(settings.supabase_url, settings.supabase_anon_key)
# ── Database Helpers ──────────────────────────────────────────────────
def insert_profile(user_id: str, full_name: str, role: str = "Medical Student") -> dict: """Create a user profile after Supabase Auth sign-up.""" client = get_supabase_client() result = client.table("profiles").insert({ "id": user_id, "full_name": full_name, "role": role, }).execute() return result.data[0] if result.data else {}
def get_profile(user_id: str) -> dict | None: """Get a user profile by ID.""" client = get_supabase_client() result = client.table("profiles").select("*").eq("id", user_id).single().execute() return result.data
def update_profile(user_id: str, updates: dict) -> dict: """Update a user profile.""" client = get_supabase_client() result = client.table("profiles").update(updates).eq("id", user_id).execute() return result.data[0] if result.data else {}
def insert_scan(scan_data: dict) -> dict: """Insert a new scan record.""" client = get_supabase_client() result = client.table("scans").insert(scan_data).execute() return result.data[0] if result.data else {}
def get_user_scans(user_id: str, scan_type: str | None = None, limit: int = 50, offset: int = 0) -> tuple[list[dict], int]: """Get scans for a user with optional filtering.""" client = get_supabase_client() query = client.table("scans").select("*", count="exact").eq("user_id", user_id) if scan_type: query = query.eq("scan_type", scan_type) query = query.order("created_at", desc=True).range(offset, offset + limit - 1) result = query.execute() return result.data or [], result.count or 0
def get_scan_by_id(scan_id: str, user_id: str) -> dict | None: """Get a single scan by ID (scoped to user).""" client = get_supabase_client() result = ( client.table("scans") .select("*") .eq("id", scan_id) .eq("user_id", user_id) .single() .execute() ) return result.data
def delete_scan(scan_id: str, user_id: str) -> bool: """Delete a scan (scoped to user).""" client = get_supabase_client() result = ( client.table("scans") .delete() .eq("id", scan_id) .eq("user_id", user_id) .execute() ) return len(result.data) > 0 if result.data else False
def get_user_stats(user_id: str) -> dict: """Get aggregated statistics for a user's scans.""" client = get_supabase_client() scans_result = client.table("scans").select("*").eq("user_id", user_id).execute() scans = scans_result.data or []
total = len(scans) critical = sum(1 for s in scans if s.get("urgency") in ("critical", "high"))
# Finding distribution dist: dict[str, int] = {} total_confidence = 0.0 finding_count = 0 for scan in scans: findings = scan.get("findings", []) for f in findings: name = f.get("name", "Other") dist[name] = dist.get(name, 0) + 1 total_confidence += f.get("confidence", 0) finding_count += 1
avg_conf = (total_confidence / finding_count) if finding_count > 0 else 0
return { "total_scans": total, "critical_findings": critical, "avg_confidence": round(avg_conf, 1), "finding_distribution": dist, }
# ── Storage Helpers ──────────────────────────────────────────────────
def _ensure_bucket(client, bucket: str = "xray-images") -> None: """Create the storage bucket if it doesn't exist yet.""" try: buckets = [b.name for b in client.storage.list_buckets()] if bucket not in buckets: client.storage.create_bucket(bucket, options={"public": True}) except Exception: pass # best-effort — upload will surface the real error if it fails
def upload_image(user_id: str, scan_id: str, file_bytes: bytes, content_type: str = "image/png") -> str: """Upload an X-ray image to Supabase Storage and return the public URL.""" client = get_supabase_client() _ensure_bucket(client) path = f"{user_id}/{scan_id}.png" client.storage.from_("xray-images").upload( path, file_bytes, {"content-type": content_type} ) url_result = client.storage.from_("xray-images").get_public_url(path) return url_result
# ── Chat Helpers ──────────────────────────────────────────────────────
def create_chat_session(user_id: str, title: str = "New Chat") -> dict: """Create a new chat session.""" client = get_supabase_client() result = client.table("chat_sessions").insert({ "user_id": user_id, "title": title, }).execute() return result.data[0] if result.data else {}
def get_chat_sessions(user_id: str) -> list[dict]: """Get all chat sessions for a user.""" client = get_supabase_client() result = ( client.table("chat_sessions") .select("*") .eq("user_id", user_id) .order("created_at", desc=True) .execute() ) return result.data or []
def user_owns_chat_session(session_id: str, user_id: str) -> bool: """Return whether a chat session belongs to a user.""" client = get_supabase_client() result = ( client.table("chat_sessions") .select("id") .eq("id", session_id) .eq("user_id", user_id) .limit(1) .execute() ) return bool(result.data)
def get_chat_messages(session_id: str, user_id: str) -> list[dict]: """Get all messages for a chat session scoped to the authenticated user.""" if not user_owns_chat_session(session_id, user_id): return [] client = get_supabase_client() result = ( client.table("chat_messages") .select("*") .eq("session_id", session_id) .order("created_at", desc=False) .execute() ) return result.data or []
def insert_chat_message(session_id: str, role: str, content: str) -> dict: """Insert a message into a chat session.""" client = get_supabase_client() result = client.table("chat_messages").insert({ "session_id": session_id, "role": role, "content": content, }).execute() return result.data[0] if result.data else {}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# XRayVision AI — YOLOv8 Fracture Detection Training\n", "**FYP: Web-Based AI Chatbot for Automated X-Ray Fracture Detection** \n", "Minhaj University Lahore — BSSE 8th Semester\n", "\n", "---\n", "\n", "## Before running: pick a dataset source\n", "\n", "### Option A — Roboflow (Recommended)\n", "1. Sign up free at [roboflow.com](https://roboflow.com)\n", "2. Go to [universe.roboflow.com](https://universe.roboflow.com)\n", "3. Search **bone fracture detection** → open any dataset\n", "4. Click **Download** → choose **YOLOv8 format** → download zip\n", "5. Upload the zip to Google Drive\n", "6. **Run cells: 1 → 2 → 3 → 4A → 5 → 6 → 7 → 8**\n", "\n", "### Option B — FracAtlas (No signup needed)\n", "1. Go to [huggingface.co/datasets/FracAtlas/FracAtlas](https://huggingface.co/datasets/FracAtlas/FracAtlas)\n", "2. Click **Files and versions** → download the zip\n", "3. Upload zip to Google Drive\n", "4. **Run cells: 1 → 2 → 3 → 4B → 5 → 6 → 7 → 8**\n", "\n", "---\n", "**First: Runtime → Change runtime type → T4 GPU → Save**" ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 1: Verify GPU ────────────────────────────────────────────\n", "!nvidia-smi\n", "import torch\n", "print(f'CUDA available : {torch.cuda.is_available()}')\n", "print(f'GPU : {torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"NONE — go to Runtime > Change runtime type > T4\"}')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 2: Install dependencies ──────────────────────────────────\n", "!pip install ultralytics -q\n", "from ultralytics import YOLO\n", "print('ultralytics OK')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 3: Mount Google Drive ────────────────────────────────────\n", "from google.colab import drive\n", "drive.mount('/content/drive')\n", "print('Drive mounted')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 4A: Extract Roboflow dataset (Option A) ──────────────────\n", "# !! Skip this cell if using FracAtlas (Option B) !!\n", "import os, zipfile\n", "\n", "# Change this to your zip file path in Google Drive\n", "ZIP_PATH = '/content/drive/MyDrive/bone-fracture-detection.zip'\n", "EXTRACT_DIR = '/content/dataset'\n", "\n", "os.makedirs(EXTRACT_DIR, exist_ok=True)\n", "print(f'Extracting {ZIP_PATH} ...')\n", "with zipfile.ZipFile(ZIP_PATH, 'r') as zf:\n", " zf.extractall(EXTRACT_DIR)\n", "print('Done!')\n", "\n", "# Show top-level structure\n", "for entry in sorted(os.listdir(EXTRACT_DIR)):\n", " print(f' {entry}')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 4B: Extract & convert FracAtlas (Option B) ───────────────\n", "# !! Skip this cell if using Roboflow (Option A) !!\n", "import os, json, shutil, zipfile\n", "from pathlib import Path\n", "from PIL import Image\n", "\n", "ZIP_PATH = '/content/drive/MyDrive/FracAtlas.zip'\n", "EXTRACT_DIR = '/content/fracatlas_raw'\n", "YOLO_DIR = '/content/dataset'\n", "\n", "# 1. Extract\n", "print('Extracting...')\n", "with zipfile.ZipFile(ZIP_PATH, 'r') as zf:\n", " zf.extractall(EXTRACT_DIR)\n", "\n", "# 2. Locate images and COCO annotation files\n", "def find_file(base, name):\n", " for p in Path(base).rglob(name):\n", " return str(p)\n", " return None\n", "\n", "images_root = find_file(EXTRACT_DIR, 'images') or EXTRACT_DIR\n", "train_json = find_file(EXTRACT_DIR, 'train.json')\n", "test_json = find_file(EXTRACT_DIR, 'test.json') or find_file(EXTRACT_DIR, 'val.json')\n", "\n", "print(f'Images root : {images_root}')\n", "print(f'Train JSON : {train_json}')\n", "print(f'Val JSON : {test_json}')\n", "\n", "# 3. COCO → YOLO converter\n", "def coco_to_yolo(coco_json_path, src_images_dir, out_images_dir, out_labels_dir):\n", " os.makedirs(out_images_dir, exist_ok=True)\n", " os.makedirs(out_labels_dir, exist_ok=True)\n", "\n", " with open(coco_json_path) as f:\n", " coco = json.load(f)\n", "\n", " id2info = {img['id']: img for img in coco['images']}\n", " # group annotations by image_id\n", " img_anns = {}\n", " for ann in coco.get('annotations', []):\n", " img_anns.setdefault(ann['image_id'], []).append(ann)\n", "\n", " for img_id, img_info in id2info.items():\n", " fname = img_info['file_name']\n", " W, H = img_info['width'], img_info['height']\n", " src_img = os.path.join(src_images_dir, os.path.basename(fname))\n", "\n", " if not os.path.exists(src_img):\n", " # search recursively\n", " found = find_file(EXTRACT_DIR, os.path.basename(fname))\n", " if found:\n", " src_img = found\n", " else:\n", " continue\n", "\n", " stem = Path(fname).stem\n", " shutil.copy(src_img, os.path.join(out_images_dir, os.path.basename(fname)))\n", "\n", " label_lines = []\n", " for ann in img_anns.get(img_id, []):\n", " cat_id = ann['category_id'] - 1 # 0-indexed\n", " x, y, w, h = ann['bbox'] # COCO: top-left x,y + w,h in pixels\n", " xc = (x + w / 2) / W\n", " yc = (y + h / 2) / H\n", " wn = w / W\n", " hn = h / H\n", " label_lines.append(f'{cat_id} {xc:.6f} {yc:.6f} {wn:.6f} {hn:.6f}')\n", "\n", " label_path = os.path.join(out_labels_dir, stem + '.txt')\n", " with open(label_path, 'w') as lf:\n", " lf.write('\\n'.join(label_lines))\n", "\n", " print(f' Converted {len(id2info)} images → {out_images_dir}')\n", "\n", "print('\\nConverting train split...')\n", "coco_to_yolo(train_json,\n", " images_root,\n", " f'{YOLO_DIR}/images/train',\n", " f'{YOLO_DIR}/labels/train')\n", "\n", "print('Converting val split...')\n", "coco_to_yolo(test_json,\n", " images_root,\n", " f'{YOLO_DIR}/images/valid',\n", " f'{YOLO_DIR}/labels/valid')\n", "\n", "print('\\nFracAtlas → YOLO conversion complete!')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 5: Build dataset.yaml ────────────────────────────────────\n", "import os, yaml\n", "\n", "DATASET_DIR = '/content/dataset'\n", "\n", "# Find images root\n", "def find_images_root(base):\n", " for root, dirs, _ in os.walk(base):\n", " if 'images' in dirs:\n", " return root\n", " return base\n", "\n", "dataset_root = find_images_root(DATASET_DIR)\n", "images_dir = os.path.join(dataset_root, 'images')\n", "val_name = 'valid' if os.path.exists(os.path.join(images_dir, 'valid')) else 'val'\n", "has_train = os.path.exists(os.path.join(images_dir, 'train'))\n", "has_val = os.path.exists(os.path.join(images_dir, val_name))\n", "\n", "# Count images\n", "def count_imgs(path):\n", " if not os.path.exists(path): return 0\n", " return sum(1 for f in os.listdir(path) if f.lower().endswith(('.jpg','.jpeg','.png')))\n", "\n", "print(f'Dataset root : {dataset_root}')\n", "print(f'Train images : {count_imgs(os.path.join(images_dir, \"train\"))}')\n", "print(f'Val images : {count_imgs(os.path.join(images_dir, val_name))}')\n", "\n", "# Auto-detect class names from data.yaml if present (Roboflow includes one)\n", "roboflow_yaml = os.path.join(dataset_root, 'data.yaml')\n", "if os.path.exists(roboflow_yaml):\n", " with open(roboflow_yaml) as f:\n", " rf = yaml.safe_load(f)\n", " CLASSES = rf.get('names', ['fracture'])\n", " print(f'Classes from Roboflow yaml: {CLASSES}')\n", "else:\n", " # FracAtlas classes\n", " CLASSES = ['Elbow Positive', 'Fingers Positive', 'Forearm Fracture',\n", " 'Humerus Fracture', 'Shoulder Fracture', 'Wrist Positive']\n", " print(f'Using FracAtlas classes: {CLASSES}')\n", "\n", "cfg = {\n", " 'path' : dataset_root,\n", " 'train' : 'images/train' if has_train else 'images',\n", " 'val' : f'images/{val_name}' if has_val else 'images/train',\n", " 'nc' : len(CLASSES),\n", " 'names' : CLASSES,\n", "}\n", "\n", "YAML_PATH = '/content/fracture_dataset.yaml'\n", "with open(YAML_PATH, 'w') as f:\n", " yaml.dump(cfg, f, default_flow_style=False)\n", "\n", "print(f'\\ndataset.yaml saved to {YAML_PATH}')\n", "!cat /content/fracture_dataset.yaml" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 6: TRAIN ─────────────────────────────────────────────────\n", "# T4 GPU: ~1 hour for 50 epochs, ~2 hours for 100 epochs\n", "from ultralytics import YOLO\n", "\n", "model = YOLO('yolov8n.pt') # swap to yolov8s.pt for +2% mAP, +30min\n", "\n", "results = model.train(\n", " data = '/content/fracture_dataset.yaml',\n", " epochs = 50,\n", " batch = 32,\n", " imgsz = 640,\n", " project = '/content/drive/MyDrive/xrayvision_training',\n", " name = 'fracture_v1',\n", " device = 0,\n", " # Medical X-ray augmentations\n", " hsv_h = 0.0, # X-rays are grayscale\n", " hsv_s = 0.0,\n", " hsv_v = 0.4, # brightness variation (exposure)\n", " degrees = 10.0, # slight rotation\n", " fliplr = 0.5,\n", " mosaic = 0.5,\n", " patience = 15, # early stopping\n", " save_period = 10,\n", " plots = True,\n", " verbose = True,\n", " exist_ok = True,\n", ")" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 7: Validate ──────────────────────────────────────────────\n", "from ultralytics import YOLO\n", "\n", "BEST = '/content/drive/MyDrive/xrayvision_training/fracture_v1/weights/best.pt'\n", "model = YOLO(BEST)\n", "metrics = model.val(data='/content/fracture_dataset.yaml')\n", "\n", "print('\\n========= FINAL RESULTS =========')\n", "print(f'mAP50 : {metrics.box.map50:.4f}')\n", "print(f'mAP50-95 : {metrics.box.map:.4f}')\n", "print(f'Precision : {metrics.box.mp:.4f}')\n", "print(f'Recall : {metrics.box.mr:.4f}')\n", "print('\\nPer-class:')\n", "for i, name in enumerate(metrics.names.values()):\n", " ap = metrics.box.ap50[i] if i < len(metrics.box.ap50) else 0\n", " print(f' {name:<30} AP50={ap:.4f}')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# ── Cell 8: Download best.pt ──────────────────────────────────────\n", "BEST = '/content/drive/MyDrive/xrayvision_training/fracture_v1/weights/best.pt'\n", "\n", "from google.colab import files\n", "files.download(BEST)\n", "\n", "print()\n", "print('After downloading:')\n", "print(' 1. Copy best.pt → backend/models/fracture_yolov8.pt')\n", "print(' 2. Edit backend/.env:')\n", "print(' YOLO_WEIGHTS_PATH=models/fracture_yolov8.pt')\n", "print(' ALLOW_GENERIC_YOLO_WEIGHTS=false')\n", "print(' 3. Restart the FastAPI server')" ], "execution_count": null, "outputs": [] } ]}12345678910111213141516171819202122fastapi==0.115.6uvicorn[standard]==0.32.1python-multipart==0.0.18pydantic==2.10.3pydantic-settings==2.7.0torch>=2.6.0torchvision>=0.21.0torchxrayvision>=1.3.0ultralytics>=8.3.0transformers>=4.45.0Pillow>=11.0.0numpy>=1.26.0opencv-python-headless>=4.10.0pydicom>=3.0.1reportlab>=4.2.5supabase>=2.9.0python-jose[cryptography]==3.3.0passlib[bcrypt]==1.7.4bcrypt>=4.2.0httpx>=0.27.0python-dotenv>=1.0.1scikit-image>=0.24.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117-- ============================================================-- XRayVision AI — Supabase Database Schema-- Run this in Supabase SQL Editor to set up all tables-- ============================================================
-- Profiles (extends Supabase auth.users)CREATE TABLE IF NOT EXISTS profiles ( id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE, full_name TEXT NOT NULL, role TEXT DEFAULT 'Medical Student', avatar_url TEXT, settings JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now());
-- Scans (core diagnostic records)CREATE TABLE IF NOT EXISTS scans ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, scan_type TEXT NOT NULL CHECK (scan_type IN ('chest', 'fracture', 'wound')), session_label TEXT, notes TEXT, image_url TEXT NOT NULL DEFAULT '', urgency TEXT CHECK (urgency IN ('critical', 'high', 'medium', 'low', 'clear')), findings JSONB NOT NULL DEFAULT '[]', agent_synthesis TEXT, agent_actions JSONB DEFAULT '[]', model_results JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT now());
-- Chat sessionsCREATE TABLE IF NOT EXISTS chat_sessions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, title TEXT DEFAULT 'New Chat', created_at TIMESTAMPTZ DEFAULT now());
-- Chat messagesCREATE TABLE IF NOT EXISTS chat_messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), session_id UUID NOT NULL REFERENCES chat_sessions(id) ON DELETE CASCADE, role TEXT NOT NULL CHECK (role IN ('user', 'assistant')), content TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT now());
-- ============================================================-- Row Level Security Policies-- ============================================================
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;ALTER TABLE scans ENABLE ROW LEVEL SECURITY;ALTER TABLE chat_sessions ENABLE ROW LEVEL SECURITY;ALTER TABLE chat_messages ENABLE ROW LEVEL SECURITY;
-- ProfilesCREATE POLICY "Users can view own profile" ON profiles FOR SELECT USING (id = auth.uid());CREATE POLICY "Users can update own profile" ON profiles FOR UPDATE USING (id = auth.uid());CREATE POLICY "Service role can insert profiles" ON profiles FOR INSERT WITH CHECK (true);
-- ScansCREATE POLICY "Users can view own scans" ON scans FOR SELECT USING (user_id = auth.uid());CREATE POLICY "Service can insert scans" ON scans FOR INSERT WITH CHECK (true);CREATE POLICY "Users can delete own scans" ON scans FOR DELETE USING (user_id = auth.uid());
-- Chat sessionsCREATE POLICY "Users can view own chat sessions" ON chat_sessions FOR SELECT USING (user_id = auth.uid());CREATE POLICY "Service can insert chat sessions" ON chat_sessions FOR INSERT WITH CHECK (true);
-- Chat messagesCREATE POLICY "Users can view own chat messages" ON chat_messages FOR SELECT USING (session_id IN (SELECT id FROM chat_sessions WHERE user_id = auth.uid()));CREATE POLICY "Service can insert chat messages" ON chat_messages FOR INSERT WITH CHECK (true);
-- ============================================================-- Indexes for performance-- ============================================================
CREATE INDEX IF NOT EXISTS idx_scans_user_id ON scans(user_id);CREATE INDEX IF NOT EXISTS idx_scans_created_at ON scans(created_at DESC);CREATE INDEX IF NOT EXISTS idx_chat_sessions_user_id ON chat_sessions(user_id);CREATE INDEX IF NOT EXISTS idx_chat_messages_session_id ON chat_messages(session_id);
-- ============================================================-- Auto-create profile on sign-up (trigger)-- ============================================================
CREATE OR REPLACE FUNCTION handle_new_user()RETURNS TRIGGER AS $$BEGIN INSERT INTO profiles (id, full_name, role) VALUES ( NEW.id, COALESCE(NEW.raw_user_meta_data->>'full_name', 'User'), COALESCE(NEW.raw_user_meta_data->>'role', 'Medical Student') ); RETURN NEW;END;$$ LANGUAGE plpgsql SECURITY DEFINER;
DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users FOR EACH ROW EXECUTE FUNCTION handle_new_user();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""YOLOv8 Fracture Detection — Fine-Tuning Script================================================Dataset: GRAZPEDWRI-DX (recommended, already in YOLO format) https://www.kaggle.com/datasets/kmader/grazpedwri-dx
Alternative datasets: FracAtlas: https://huggingface.co/datasets/FracAtlas/FracAtlas MURA (Stanford): https://stanfordmlgroup.github.io/competitions/mura/
Setup: pip install ultralytics kaggle
Download GRAZPEDWRI-DX from Kaggle: 1. Get your API token from https://www.kaggle.com/settings → API → Create Token 2. Place kaggle.json in ~/.kaggle/ 3. Run: kaggle datasets download -d kmader/grazpedwri-dx -p data/grazpedwri-dx --unzip
Usage: python train_fracture_model.py --dataset data/grazpedwri-dx --epochs 100 python train_fracture_model.py --dataset data/grazpedwri-dx --epochs 50 --model yolov8s.pt
After training, copy the best weights: cp runs/fracture/train/weights/best.pt models/fracture_yolov8.pt
Then update backend/.env: YOLO_WEIGHTS_PATH=models/fracture_yolov8.pt ALLOW_GENERIC_YOLO_WEIGHTS=false"""
from __future__ import annotations
import argparseimport osimport shutilimport sysfrom pathlib import Path
# ── Dataset YAML generation ──────────────────────────────────────────
def build_dataset_yaml(dataset_path: str, output_path: str = "fracture_dataset.yaml") -> str: """Create a YOLO dataset config pointing to the local dataset.""" dataset = Path(dataset_path).resolve()
# GRAZPEDWRI-DX ships with train/ and valid/ splits train_path = dataset / "images" / "train" val_path = dataset / "images" / "valid"
if not train_path.exists(): # Try flat structure train_path = dataset / "train" / "images" val_path = dataset / "valid" / "images"
if not train_path.exists(): print(f"[WARN] Expected train images at {train_path} — verify dataset structure.")
yaml_content = f"""# GRAZPEDWRI-DX Fracture Detection Dataset# https://www.kaggle.com/datasets/kmader/grazpedwri-dxpath: {str(dataset)}
train: images/trainval: images/valid
# Classes — GRAZPEDWRI-DX classesnc: 10names: 0: boneanomaly 1: bonelesion 2: foreignbody 3: fracture 4: metal 5: periostealreaction 6: pronationsign 7: softtissue 8: text 9: hardware
# Notes:# The primary class of interest is 'fracture' (index 3).# During inference, XRayVision AI reports any detected class# that relates to bone damage."""
with open(output_path, "w") as f: f.write(yaml_content)
print(f"[OK] Dataset YAML written to: {output_path}") return output_path
# ── Training ─────────────────────────────────────────────────────────
def train( dataset_yaml: str, base_model: str = "yolov8n.pt", epochs: int = 100, batch: int = 16, imgsz: int = 640, project: str = "runs/fracture", name: str = "train", device: str = "0", # GPU 0; use "cpu" for CPU-only) -> Path: """Fine-tune YOLOv8 on the fracture dataset.""" try: from ultralytics import YOLO except ImportError: sys.exit("ultralytics not installed. Run: pip install ultralytics")
print(f"\n{'='*60}") print(f" XRayVision AI — YOLOv8 Fracture Fine-Tuning") print(f"{'='*60}") print(f" Base model : {base_model}") print(f" Dataset : {dataset_yaml}") print(f" Epochs : {epochs}") print(f" Batch size : {batch}") print(f" Image size : {imgsz}px") print(f" Device : {device}") print(f"{'='*60}\n")
model = YOLO(base_model)
results = model.train( data=dataset_yaml, epochs=epochs, batch=batch, imgsz=imgsz, project=project, name=name, device=device, # Medical imaging — use slower, more accurate augmentations augment=True, hsv_h=0.0, # X-rays are grayscale, skip hue shift hsv_s=0.0, # Skip saturation shift hsv_v=0.4, # Vary brightness (simulates exposure differences) degrees=10.0, # Mild rotation (patient positioning variation) translate=0.1, scale=0.5, shear=0.0, flipud=0.0, fliplr=0.5, # Horizontal flip is anatomically valid mosaic=0.5, # Hyperparameters tuned for medical images lr0=0.001, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, patience=20, # Early stopping save_period=10, val=True, plots=True, # Class weights to prioritize fracture detection cls=0.5, box=7.5, dfl=1.5, verbose=True, exist_ok=True, )
best_weights = Path(project) / name / "weights" / "best.pt" print(f"\n[DONE] Training complete!") print(f" Best weights: {best_weights.resolve()}") print(f" mAP50: {results.results_dict.get('metrics/mAP50(B)', 'N/A')}") print(f" mAP50-95: {results.results_dict.get('metrics/mAP50-95(B)', 'N/A')}")
return best_weights
# ── Validation ───────────────────────────────────────────────────────
def validate(weights_path: str, dataset_yaml: str, imgsz: int = 640) -> None: """Run validation on the val split and print metrics.""" from ultralytics import YOLO
print(f"\n[INFO] Validating {weights_path} ...") model = YOLO(weights_path) metrics = model.val(data=dataset_yaml, imgsz=imgsz)
print(f"\n[RESULTS]") print(f" mAP50 : {metrics.box.map50:.4f}") print(f" mAP50-95 : {metrics.box.map:.4f}") print(f" Precision : {metrics.box.mp:.4f}") print(f" Recall : {metrics.box.mr:.4f}")
print("\n[Per-class]") for i, name in enumerate(metrics.names.values()): ap = metrics.box.ap[i] if i < len(metrics.box.ap) else 0 print(f" {name:<30} AP50={ap:.4f}")
# ── Deploy helpers ────────────────────────────────────────────────────
def deploy(best_weights: str, target: str = "models/fracture_yolov8.pt") -> None: """Copy best weights to the backend models/ directory.""" target_path = Path(target) target_path.parent.mkdir(parents=True, exist_ok=True) shutil.copy(best_weights, target_path) print(f"\n[DEPLOYED] Weights copied to: {target_path.resolve()}") print(f"\nNext steps:") print(f" 1. Update backend/.env:") print(f" YOLO_WEIGHTS_PATH=models/fracture_yolov8.pt") print(f" ALLOW_GENERIC_YOLO_WEIGHTS=false") print(f" 2. Restart the FastAPI server.")
# ── CLI ───────────────────────────────────────────────────────────────
def main() -> None: parser = argparse.ArgumentParser( description="Fine-tune YOLOv8 for fracture detection (XRayVision AI FYP)" ) parser.add_argument("--dataset", required=True, help="Path to GRAZPEDWRI-DX dataset root") parser.add_argument("--model", default="yolov8n.pt", help="Base YOLO model (yolov8n/s/m/l/x.pt)") parser.add_argument("--epochs", type=int, default=100) parser.add_argument("--batch", type=int, default=16) parser.add_argument("--imgsz", type=int, default=640) parser.add_argument("--device", default="0", help="GPU id (0,1,...) or 'cpu'") parser.add_argument("--validate-only", metavar="WEIGHTS", default=None, help="Skip training and only validate existing weights") parser.add_argument("--deploy", action="store_true", help="Copy best.pt to models/fracture_yolov8.pt after training") args = parser.parse_args()
yaml_path = build_dataset_yaml(args.dataset)
if args.validate_only: validate(args.validate_only, yaml_path, args.imgsz) return
best = train( dataset_yaml=yaml_path, base_model=args.model, epochs=args.epochs, batch=args.batch, imgsz=args.imgsz, device=args.device, )
validate(str(best), yaml_path, args.imgsz)
if args.deploy: deploy(str(best))
if __name__ == "__main__": main().gitignoreAdded+50
DockerfileAdded+17
README.mdAdded+67
app/__init__.pyAdded+1
app/config.pyAdded+66
app/main.pyAdded+140
app/models/__init__.pyAdded+1
app/models/schemas.pyAdded+202
app/routers/__init__.pyAdded+1
app/routers/analyze.pyAdded+247
app/routers/auth.pyAdded+164
app/routers/chat.pyAdded+78
app/routers/clinics.pyAdded+174
app/routers/diet.pyAdded+52
app/routers/scans.pyAdded+432
app/routers/stats.pyAdded+46
app/services/__init__.pyAdded+1
app/services/auth_service.pyAdded+79
app/services/chatbot_service.pyAdded+128
app/services/chest_model.pyAdded+139
app/services/diet_service.pyAdded+330
app/services/fracture_classifier.pyAdded+99
app/services/fracture_model.pyAdded+170
app/services/image_preprocess.pyAdded+116
app/services/openrouter_agent.pyAdded+262
app/services/openrouter_client.pyAdded+58
app/services/wound_model.pyAdded+127
app/utils/__init__.pyAdded+1
app/utils/supabase_client.pyAdded+213
colab_train_fracture.ipynbAdded+341
requirements.txtAdded+22
supabase_schema.sqlAdded+117
train_fracture_model.pyAdded+247