Skip to content

Repository files navigation

🧠 BrainScanner — AI-Powered Brain Tumor Detection Platform

Deep-Learning neuro-imaging meets LangChain-powered AI chat.
Upload an MRI scan → get a clinical-grade classification → chat with an AI assistant → download a medical-grade PDF report.

Accuracy: 95.4%  |  Precision: 94.8%  |  Recall: 93.7%  |  F1 Score: 94.2%

BrainScanner Landing Page


📌 Table of Contents


✨ Overview

BrainScanner is a full-stack, AI-powered brain tumor detection and clinical-reporting platform. It combines:

  • A custom-trained CNN built on Transfer Learning (TensorFlow/Keras, ~95.4% accuracy)
  • A LangChain + Groq dual-persona chatbot (patient-mode "Aura" & doctor-mode clinical assistant)
  • A thread-safe CSV database (7 tables, no SQL server needed)
  • An SMTP HTML welcome-email system (sent on every signup)
  • A ReportLab medical-certificate PDF generator
  • A FastAPI backend serving a stunning HTML/CSS/JS multi-page frontend

Core Capabilities

Feature Description
🧠 AI Tumor Classification CNN classifies MRI scans into Glioma, Meningioma, Pituitary, or No Tumor with confidence %
💬 Dual-Mode AI Chatbot LangChain + Groq LLM with separate Patient (Aura) and Doctor (Clinical) system prompts
📄 PDF Report Generation ReportLab generates medical-certificate-style PDFs with stamps, signatures and watermarks
🗄️ CSV Database Thread-safe, 7-table CSV data layer for users, scans, reports, chat history and analytics
📧 Welcome Emails SMTP-based HTML welcome emails auto-sent on every signup
👤 Multi-Role System Separate Patient, Doctor, and Admin dashboards with role-gated APIs
📊 Admin Analytics Live command center: monthly scan trends, tumor-distribution donut chart, platform KPIs

🧬 Model — Transfer Learning Deep Dive

The heart of BrainScanner is a pre-trained CNN fine-tuned for brain tumor classification from MRI images.

What is Transfer Learning?

Transfer learning is a technique where a model pre-trained on a huge dataset (ImageNet — 14M+ images, 1000 classes) is adapted for a new related task. Instead of training from scratch, we reuse the learned feature detectors (edges, textures, shapes) and only re-train the final classification layers on our brain tumor data.

  ImageNet Pre-trained Weights  (VGG16 / EfficientNet / ResNet)
          │
          ▼
  ┌────────────────────────────────────────┐
  │   FROZEN Base CNN Layers               │  ← Reused feature extractor
  │   Conv blocks: edges, textures,        │    (weights never changed)
  │   shapes, high-level patterns          │
  └────────────────────────────────────────┘
          │
  ┌────────────────────────────────────────┐
  │   CUSTOM Classification Head           │  ← Fine-tuned on MRI data
  │   GlobalAveragePooling2D               │
  │   Dense(256, activation='relu')        │
  │   Dropout(0.5)                         │
  │   Dense(4,  activation='softmax')      │
  └────────────────────────────────────────┘
          │
          ▼
  [ Glioma | Meningioma | Pituitary | No Tumor ]

Notebook: Brain Tumor.ipynb

The full training pipeline is in the Jupyter notebook. Here is what it covers:

1. Dataset Preparation

Classes    = ["glioma", "meningioma", "notumor", "pituitary"]
Input Size = 150 x 150 pixels (RGB)
Train/Test = 80% / 20% split
Augmentation: RandomRotation, HorizontalFlip, Zoom, BrightnessContrast

2. Two-Phase Fine-Tuning Strategy

Phase 1 — Feature Extraction  (fast convergence)
  • All base layers FROZEN
  • Only the new Dense head is trained
  • Optimizer: Adam  |  LR: 1e-3  |  Epochs: 10-15

Phase 2 — Fine-Tuning  (precision boost)
  • Top N layers of the base model UN-FROZEN
  • End-to-end training at a very low learning rate
  • Optimizer: Adam  |  LR: 1e-5  |  Epochs: 5-10
  • Prevents "catastrophic forgetting" of ImageNet features

3. Model Architecture Code

from tensorflow.keras.applications import EfficientNetB0   # or VGG16 / ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.models import Model

base_model = EfficientNetB0(weights='imagenet', include_top=False, input_shape=(150,150,3))
base_model.trainable = False                        # Freeze base

x = GlobalAveragePooling2D()(base_model.output)
x = Dense(256, activation='relu')(x)
x = Dropout(0.5)(x)
output = Dense(4, activation='softmax')(x)          # 4 tumor classes

model = Model(inputs=base_model.input, outputs=output)
model.compile(
    optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)

4. Training Results

Metric Value
Test Accuracy 95.4%
Precision 94.8%
Recall 93.7%
F1 Score 94.2%

The notebook also includes:

  • 📈 Training vs Validation loss & accuracy curves
  • 🔲 4×4 Confusion matrix across all tumor classes
  • 🔥 Grad-CAM heatmaps — regions the model focused on
  • 📋 Per-class precision, recall, F1 breakdown

5. Model Export

model.save("brain_tumor_model.h5")   # Keras HDF5 format — ~134 MB on disk

How model.py Serves Predictions

The .h5 model is loaded via a lazy, thread-safe singleton — loaded once, stays in memory:

_model      = None
_model_lock = threading.Lock()

def _load_model():
    global _model
    with _model_lock:
        if _model is None:
            from tensorflow.keras.models import load_model
            _model = load_model("brain_tumor_model.h5")
    return _model

def predict_image(image_bytes: bytes) -> dict:
    # Preprocess
    img = Image.open(io.BytesIO(image_bytes)).convert("RGB").resize((150, 150))
    arr = np.asarray(img, dtype="float32") / 255.0      # normalise [0,1]
    arr = np.expand_dims(arr, axis=0)                    # (1, 150, 150, 3)

    # Inference
    probs = _load_model().predict(arr, verbose=0)[0]     # softmax output

    # Return structured result
    idx   = int(np.argmax(probs))
    label = CLASS_NAMES[idx]                             # e.g. "meningioma"
    return {
        "predicted_class" : label,
        "predicted_label" : CLASS_DISPLAY[label],        # "Meningioma Tumor"
        "confidence"      : round(float(probs[idx]) * 100, 2),
        "probabilities"   : { CLASS_DISPLAY[c]: round(float(p)*100,2)
                              for c,p in zip(CLASS_NAMES, probs) },
        "has_tumor"       : label != "notumor",
        "processing_time" : elapsed_seconds,
        "model_version"   : "brain_tumor_cnn_v1",
        "is_mock"         : False,
    }

Graceful Degradation: If TensorFlow or the .h5 file is unavailable, the module auto-falls-back to a deterministic mock predictor (seeded from the SHA-256 of the image bytes). The entire API and frontend remain fully functional for demos without a GPU.


🔗 LangChain AI Chatbot Architecture

llm.py uses LangChain + Groq's ultra-fast inference API (Llama 3.3 70B) to power two completely isolated AI personas.

How LangChain Builds the Conversation

User Question
      │
      ▼
┌──────────────────────────────────────────────────┐
│                 llm.py  chat()                    │
│                                                  │
│  1. Determine role:  "patient" → Aura            │
│                      "doctor"  → Clinical mode   │
│                                                  │
│  2. select_system_prompt(role, user_subrole)     │
│                                                  │
│  3. Build LangChain message chain:               │
│       SystemMessage(system_prompt)               │
│       HumanMessage(history[-10].question)  ─┐   │
│       AIMessage   (history[-10].answer  )   │   │
│       ...  (last 10 turns of context)   ────┘   │
│       HumanMessage(current_question)             │
│                                                  │
│  4. ChatGroq.invoke(messages)  → AIMessage       │
│  5. Return { role, answer, source, response_time}│
└──────────────────────────────────────────────────┘

The Two AI Personas

🟦 "Aura" — Patient Support Assistant

ROLE   : Patient-facing support bot. NOT a doctor.
PURPOSE: Explain tumor types & grades in plain language.
         Describe treatment modalities generally.
         Help build question lists for appointments.
         Translate medical / radiology jargon.

HARD LIMITS (never crossed):
  ✗ Interpret or comment on this patient's specific scan
  ✗ State or imply a diagnosis / prognosis
  ✗ Recommend drug dosages or treatment plans
  ✗ Replace the care team

SAFETY ROUTING:
  • Emergency symptoms  → "Call emergency services / go to ER NOW"
  • Crisis / suicidal   → crisis line + immediate care team redirect

TONE: Warm · Calm · Plain language · Short paragraphs · Empathetic

🟩 Clinical Decision Support — Doctor Mode

ROLE   : Clinical decision-support for licensed physicians.
PURPOSE: Tumor-board-style case synthesis.
         Surgical planning (resectability, approach).
         Treatment pathway per WHO CNS5 / NCCN / EANO.
         Differential reasoning: imaging → differentials → what confirms.

ROLE-AWARE OUTPUT:
  Resident/Assistant → teaching rationale + escalation flags
  Attending/Senior   → concise, high-density, decision-focused

HARD LIMITS (never crossed):
  ✗ Present model output as a confirmed diagnosis
  ✗ Give specific drug dosing for a real patient
  ✗ Fabricate guideline citations or trial statistics

TONE: Professional clinical register · Structured headers · Evidence-based

LangChain Code (Actual Implementation)

from langchain_groq      import ChatGroq
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage

llm = ChatGroq(
    model       = os.getenv("LLM_MODEL", "llama-3.3-70b-versatile"),
    api_key     = os.getenv("GROQ_API_KEY"),
    temperature = float(os.getenv("LLM_TEMPERATURE", "0.7")),
    max_tokens  = 512,
)

messages = [SystemMessage(content=system_prompt)]

for turn in (history or [])[-10:]:          # keep last 10 turns
    if turn.get("question"):
        messages.append(HumanMessage(content=turn["question"]))
    if turn.get("answer"):
        messages.append(AIMessage   (content=turn["answer"]))

messages.append(HumanMessage(content=current_question))

response = llm.invoke(messages)
answer   = response.content                 # final reply string

Emergency / Crisis Safety Net (Always On)

Even with no API key (fallback mode), keyword detection runs first:

EMERGENCY_TERMS = ["seizure","unconscious","severe headache","lost vision",
                   "slurred speech","numbness","sudden weakness", ...]
CRISIS_TERMS    = ["suicide","kill myself","end my life","no reason to live","hopeless"]

# Checked BEFORE any LLM call — cannot be bypassed
if any(t in question.lower() for t in CRISIS_TERMS):
    return crisis_response()        # crisis line + care team redirect
if any(t in question.lower() for t in EMERGENCY_TERMS):
    return emergency_response()     # "Go to ER NOW"

⚙️ Backend Architecture

FastAPI (main.py) wires four routers and serves the static frontend:

FastAPI App  ─  http://localhost:8000
│
├─ /api/auth/*    ──►  login_page.py   Signup · Login · Me · Logout
├─ /api/scans/*   ──►  scans.py        Analyze · Report · Download · Review
├─ /api/chat/*    ──►  chat.py         Patient & Doctor NeuroBot
├─ /api/admin/*   ──►  admin.py        Overview · Trend · Tables · Analytics
├─ /api/health    ──►  main.py         Health check + model info
│
└─ Static Frontend ─►  /css  /js  /images
                        /   /login.html  /select.html
                        /patient.html   /doctor.html  /admin.html

End-to-End Scan Flow

① User drags & drops MRI image on Patient/Doctor dashboard
         │
         ▼
② POST /api/scans/analyze  (multipart file upload)
         │
         ├─ Validate extension  (.jpg / .png / .bmp / .tif / .tiff)
         ├─ model.predict_image(raw_bytes)
         │       ├─ PIL: open → RGB → resize 150×150
         │       ├─ NumPy: normalise to [0, 1]
         │       └─ Keras model.predict(arr)  → softmax probabilities
         ├─ Write raw bytes to UPLOAD_DIR/{scan_id}.jpg
         ├─ db.insert("mri_scans", scan_row)
         └─ db.update("patients", bump total_scans + last_scan_date)
         │
         ▼
③ Frontend renders: Classification label · Confidence % · Probability bars
         │
         ▼
④ POST /api/scans/{scan_id}/report
         │
         ├─ report.generate_report(scan, patient)
         │       └─ ReportLab → Medical Certificate PDF
         └─ db.insert("reports", report_row)
         │
         ▼
⑤ GET /api/scans/{scan_id}/report/download
         └─ FileResponse(pdf_path, media_type="application/pdf")

Signup → Welcome Email Flow

POST /api/auth/signup
  ├─ Validate: email unique, password len ≥ 4, role ∈ {patient, doctor}
  ├─ db.insert("users", {...})
  ├─ db.insert("patients" | "doctors", role-profile row)
  ├─ send_welcome_email(email, username)  ← best-effort, never blocks
  └─ Return: HMAC-SHA256 token + user dict

POST /api/auth/login
  ├─ email+password+role check
  └─ Return: new HMAC-SHA256 token (12h TTL)

GET /api/auth/me  [Bearer token required]
  └─ Return: user dict + role-specific profile

🗄️ Database Layer

database.py provides a CSV-backed, thread-safe data layer — no SQL server, no migrations, no setup beyond Python.

Schema — 7 Tables

📂 Database/
│
├── users.csv
│     user_id | role | username | email | password | status | created_at | last_login
│
├── patients.csv
│     patient_id | user_id | full_name | email | phone | gender | date_of_birth
│     address | registration_date | total_scans | total_reports | last_scan_date | account_status
│
├── doctors.csv
│     doctor_id | user_id | doctor_name | email | phone | specialization
│     hospital_name | license_number | registration_date | total_reviews | last_login | account_status
│
├── mri_scans.csv
│     scan_id | patient_id | upload_date | mri_file_name | mri_file_path
│     predicted_tumor | prediction_confidence | report_id | doctor_review_status
│     doctor_id | review_date | model_version | processing_time
│
├── reports.csv
│     report_id | patient_id | scan_id | predicted_tumor | confidence_score
│     report_path | generated_date | download_count | report_status
│
├── chat_history.csv
│     chat_id | session_id | user_role | user_id | question | answer | timestamp
│
└── admin_analytics.csv
      analytics_id | date | total_patients | total_doctors | total_scans | total_reports
      total_chats | glioma_count | meningioma_count | pituitary_count | no_tumor_count
      avg_confidence | avg_response_time

CRUD API

# READ
db.read_all("mri_scans")                              # All rows → list[dict]
db.find("mri_scans", patient_id="pat_abc123")        # Filter rows
db.find_one("users", email="user@example.com")        # First match or None
db.count("mri_scans", patient_id="pat_abc123")       # Count matches

# WRITE
db.insert("mri_scans", {...})                         # Append row
db.update("patients", {"patient_id": x},              # Partial update
          {"total_scans": 5, "last_scan_date": now})
db.delete("users", user_id="usr_xyz")                 # Delete matching rows

# ADMIN AGGREGATIONS
db.tumor_distribution()   # → {"glioma": 42, "meningioma": 31, ...}
db.average_confidence()   # → 94.3
db.snapshot_analytics()   # → full admin KPI row for today

Thread Safety

_LOCK = threading.RLock()   # module-level reentrant lock

def insert(table, row):
    with _LOCK:             # exclusive access during write
        _ensure_file(table)
        with _path(table).open("a", newline="", encoding="utf-8") as f:
            csv.DictWriter(f, fieldnames=SCHEMAS[table]).writerow(clean_row)

All writes (insert, update, delete) acquire the lock before touching the file — safe for concurrent FastAPI requests with no external infrastructure.


📧 Welcome Email System

Every successful signup fires a beautiful HTML welcome email via email_create.py.

Flow

POST /api/auth/signup
        │
        └── send_welcome_email(to_email, username)
                │
                ├─ Load  templates/welcome_email.html
                ├─ Sub   {{USERNAME}} → "Hey, Mohit"
                ├─ Build MIMEMultipart("alternative")
                │     ├─ MIMEText(plain_fallback, "plain")
                │     └─ MIMEText(html_body,      "html")
                ├─ SMTP(host, port, timeout=15)
                ├─ server.ehlo()  →  server.starttls()  →  server.login()
                └─ server.sendmail(sender, [to_email], msg.as_string())

Email Template Design

Element Detail
Background Deep-space gradient #1A0B2E → #050813 → #08201D
Brand accent Electric cyan #7DF9FF
Feature cards Glassmorphism rgba(255,255,255,0.05) with 12px radius
🧠 Card 1 Deep-Learning Analysis — clinical-grade classification in 3 s
📄 Card 2 Instant PDF Reports — downloadable right after the scan
💬 Card 3 AI Health Chatbot — straight answers about your results
CTA Button "Go to Dashboard" — cyan on dark
Footer Privacy · Terms · Unsubscribe

.env Configuration

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your@gmail.com
SMTP_PASSWORD=your_google_app_password
SMTP_FROM=Brain Scanner <your@gmail.com>
SMTP_USE_TLS=true

Dry-run mode: If any SMTP env var is missing, the email is logged to console and signup completes normally. Errors are caught and never surface to the user.


📄 PDF Report Generation

report.py uses ReportLab to produce a professional Medical Certificate PDF for every scan.

Report Layout

┌─────────────────────────────────────────────────────┐
│   +   CITY GENERAL HOSPITAL                         │
│       OFFICIAL MEDICAL DOCUMENTATION                │
│ ───────────────────────────────────────────────     │
│                                                     │
│              MEDICAL CERTIFICATE                    │
│                                                     │
│  Date: _24 July 2026__                              │
│                                                     │
│  Name: _Mohit Jadav__________  Age: ____________   │
│  Gender: ___________                                │
│                                                     │
│  Diagnosis: MRI scan indicates Meningioma Tumor     │
│             (Confidence: 97.62%)                    │
│                                                     │
│  Recommendations: Immediate consultation with a     │
│                   neurologist. Further clinical     │
│                   correlation and follow-up         │
│                   imaging required.                 │
│                                                     │
│  ________________  [🔴 BRAIN SCANNER]  Dr. M~~~~~  │
│   Patient Signature     Official Stamp  Dr. Sign   │
└─────────────────────────────────────────────────────┘

Premium PDF Features

Feature Implementation
Watermark Diagonal "BRAIN SCANNER" text, rose-pink, 45° rotation
Official Stamp Two concentric red circles with tumor type + date + "CONFIDENTIAL"
Doctor Signature Vector-drawn handwritten "M" strokes with sweep line via ReportLab paths
Dotted fill lines Dashed underlines (setDash(2,2)) for every form field
Color scheme Off-white #F4F4F0 bg · Navy #0f172a text · Blue #2563eb italic fills
Text fallback Auto-falls back to clean .txt report if ReportLab is not installed

🖥️ Frontend Overview

The frontend (Fronted_page/) is pure HTML + Vanilla CSS + JavaScript served directly by FastAPI — zero build step, zero npm.

Pages

Page File Purpose
🏠 Landing index.html Hero · Features · 4-step workflow · Impact stats · CTA
🔐 Login/Signup login.html Animated neon-tile background · Sign In / Create Account tabs
🧭 Role Selector select.html Post-login: Patient / Doctor / Admin picker
🧑 Patient patient.html Drag-and-drop MRI upload · AI result card · NeuroBot · PDF download
👨‍⚕️ Doctor doctor.html Model metrics header · Clinical MRI review · NeuroBot Consult · Report export
🔧 Admin admin.html Live line chart · Tumor donut chart · Platform KPI cards

Design Highlights

  • Color palette: Deep dark base + magenta/orange/olive gradients + #7DF9FF brand cyan
  • Glassmorphism: rgba card backgrounds with backdrop-filter: blur()
  • Typography: Inter-style system stack — large bold headings
  • Animations: Cyan scan-line sweep on MRI preview · floating particles on login · CSS hover transitions
  • Quote ticker: Auto-scrolling medical quotes banner between sections
  • Responsive: CSS Grid + Flexbox — desktop and tablet

How the Frontend Talks to the Backend

const token = sessionStorage.getItem("bs_session");   // HMAC Bearer token

// ① Upload & analyze MRI
const form = new FormData();
form.append("file", mriFile);
const res  = await fetch("/api/scans/analyze", {
    method: "POST",
    headers: { "Authorization": `Bearer ${token}` },
    body: form
});
const { result } = await res.json();
// result.predicted_label → "Meningioma Tumor"
// result.confidence      → 97.62

// ② Chat with NeuroBot
const chat = await fetch("/api/chat/message", {
    method: "POST",
    headers: { "Authorization": `Bearer ${token}`,
               "Content-Type": "application/json" },
    body: JSON.stringify({ role: "patient",
                           message: "What does meningioma mean?" })
});

📸 Screenshots

🏠 Landing Page — Hero

Landing Hero

🌟 Features Section — Tumor Analysis · NeuroBot · PDF Reports

Features

🔄 How It Works — 4 Steps from Scan to Insight

Workflow

🌐 Call to Action + Footer

CTA Footer

🔐 Login / Sign Up — Animated Neon Tile Background

Login Signup

🧭 Role Selection — Welcome, Mohit

Role Select

🧑 Patient Dashboard — MRI Upload + NeuroBot Assistant

Patient Dashboard

📁 MRI File Picker — Meningioma Test Images

MRI Browser

🧬 MRI Loaded with Cyan Scan-Line Animation

Scan Line

📊 AI Result — Meningioma 97.6% + Probability Distribution

Result Meningioma

💬 NeuroBot Chat — "What does my result mean?"

NeuroBot Patient

📄 Generated Medical Certificate PDF — City General Hospital

PDF Report

👨‍⚕️ Doctor Dashboard — Model Metrics + Patient MRI Review

Doctor Dashboard

👨‍⚕️ Doctor — Pituitary Tumor 100.0% Confidence Report

Doctor Pituitary

🤖 Doctor NeuroBot Consult — Surgical Options Query

NeuroBot Doctor

🤖 NeuroBot Full Clinical Answer — Craniotomy & Biopsy Explained

NeuroBot Full

📊 Admin Command Center — Live Platform Analytics

Admin Dashboard


🚀 Getting Started

Prerequisites

  • Python 3.10+
  • TensorFlow 2.x (optional — mock predictor works without it)
  • Free Groq API key for the AI chatbot

1. Clone & Install

git clone https://github.com/your-username/BrainScanner.git
cd BrainScanner/Backed_code
pip install -r requirements.txt

2. Configure .env

Create Backed_code/.env:

# ── Model ─────────────────────────────────────────────────
MODEL_PATH=../brain_tumor_model.h5
MODEL_VERSION=brain_tumor_cnn_v1
MODEL_IMG_SIZE=150

# ── Database ──────────────────────────────────────────────
DATABASE_DIR=../Database

# ── LLM / Chatbot (Groq) ─────────────────────────────────
GROQ_API_KEY=gsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxx
LLM_MODEL=llama-3.3-70b-versatile
LLM_TEMPERATURE=0.7

# ── Welcome Email (optional) ─────────────────────────────
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your@gmail.com
SMTP_PASSWORD=your_app_password
SMTP_FROM=Brain Scanner <your@gmail.com>
SMTP_USE_TLS=true

# ── PDF Reports ───────────────────────────────────────────
REPORTS_OUTPUT_DIR=./generated_reports

# ── Auth ──────────────────────────────────────────────────
SESSION_SECRET=change-this-in-production-please
SESSION_TTL_SECONDS=43200

# ── Server ────────────────────────────────────────────────
HOST=127.0.0.1
PORT=8000
RELOAD=1
LOG_LEVEL=INFO

3. Run

cd Backed_code
uvicorn main:app --reload --port 8000
# or:
python main.py

Open http://localhost:8000 — the landing page loads instantly.

4. Default Admin Account

Email:    admin@brainscanner.com
Password: admin

Patient/Doctor accounts are created via the Create Account tab on the login page.

5. Interactive API Docs

http://localhost:8000/docs    # Swagger UI — try every endpoint live
http://localhost:8000/redoc   # ReDoc — clean reference

📡 API Reference

Method Endpoint Auth Description
POST /api/auth/signup — Register new patient or doctor
POST /api/auth/login — Login, returns 12h HMAC token
GET /api/auth/me ✅ Current user + role profile
POST /api/auth/logout ✅ Logout (client drops token)
POST /api/scans/analyze ✅ Upload MRI → run CNN inference
GET /api/scans/mine ✅ List all scans for logged-in patient
POST /api/scans/{id}/report ✅ Generate PDF medical certificate
GET /api/scans/{id}/report/download ✅ Stream PDF file
POST /api/scans/{id}/review ✅ Doctor Approve / reject scan
POST /api/chat/message ✅ Send message to NeuroBot
GET /api/admin/overview ✅ Admin Platform stats snapshot
GET /api/admin/trend ✅ Admin Monthly scan trend data
GET /api/admin/tables ✅ Admin Full data tables
GET /api/health — Health check + model info
GET /api/model/info — Model version, classes, mode

📁 Project Structure

BrainScanner/
│
├── 📓 Brain Tumor.ipynb               # Full CNN training & evaluation notebook
├── 🤖 brain_tumor_model.h5            # Trained Keras model (~134 MB)
├── 📧 brain_scanner_welcome_email.html # Welcome email HTML preview
│
├── 📂 Backed_code/                    # FastAPI Python backend
│   ├── main.py                        # App factory + router wiring + static serving
│   ├── model.py                       # CNN inference — lazy singleton + mock fallback
│   ├── llm.py                         # LangChain + Groq dual-persona chatbot
│   ├── database.py                    # Thread-safe CSV CRUD layer (7 tables)
│   ├── login_page.py                  # Auth router: signup/login/me/logout
│   ├── scans.py                       # Scan analysis + report + review router
│   ├── chat.py                        # Chat router (patient & doctor)
│   ├── admin.py                       # Admin analytics router
│   ├── report.py                      # ReportLab medical certificate generator
│   ├── email_create.py                # SMTP HTML welcome email sender
│   ├── model_testing.py               # Model evaluation: confusion matrix, metrics
│   ├── requirements.txt               # Python dependencies
│   ├── .env                           # Environment variables (not committed)
│   └── templates/
│       └── welcome_email.html         # HTML email template
│
├── 📂 Database/                       # Auto-created CSV storage
│   ├── users.csv
│   ├── patients.csv
│   ├── doctors.csv
│   ├── mri_scans.csv
│   ├── reports.csv
│   ├── chat_history.csv
│   └── admin_analytics.csv
│
├── 📂 Fronted_page/                   # Static HTML/CSS/JS frontend
│   ├── index.html                     # Landing page
│   ├── login.html                     # Authentication
│   ├── select.html                    # Role picker
│   ├── patient.html                   # Patient dashboard
│   ├── doctor.html                    # Doctor dashboard
│   ├── admin.html                     # Admin command center
│   ├── css/                           # Stylesheets
│   ├── js/                            # JavaScript modules
│   └── images/                        # Static images & assets
│
└── 📂 Screenshots/                    # 17 App screenshots

🛠️ Tech Stack

Layer Technology Purpose
Web Framework FastAPI 0.110+ + Uvicorn REST API, CORS, static file serving
Deep Learning TensorFlow 2.x / Keras CNN model training & inference
Transfer Learning Pre-trained ImageNet backbone Feature extraction (frozen base layers)
AI Chatbot LangChain 0.2+ + ChatGroq Message chaining, conversation memory
LLM Meta Llama 3.3 70B (via Groq) Natural language generation
PDF Generation ReportLab Medical certificate with stamps & signatures
Email Python smtplib + MIMEMultipart SMTP HTML welcome emails
Database CSV files + threading.RLock Thread-safe flat-file persistence
Auth HMAC-SHA256 Bearer tokens Stateless session management (12h TTL)
Frontend HTML5 + CSS3 + Vanilla JS Multi-page application, no build step
Image Processing Pillow + NumPy MRI preprocessing pipeline
Data Science scikit-learn + matplotlib Model evaluation, confusion matrix
Config python-dotenv Environment variable management

📜 Disclaimer

BrainScanner is an educational and research project. All AI model outputs are provisional and must be reviewed and confirmed by a qualified physician via clinical review, and where appropriate, histopathological or molecular analysis. This platform does not establish a doctor–patient relationship and is not a substitute for professional medical diagnosis, advice, or treatment.


🤝 Contributing

Pull requests are welcome! For major changes, please open an issue first.

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License — see the LICENSE file for details.


Made with ❤️ and 🧠 by Mohit Jadav

"See the unseen. Detect gliomas before they speak."

⭐ Star this repo if it helped you!

About

An end-to-end AI-powered Brain Tumor Detection Platform built with TensorFlow, FastAPI, LangChain, and Groq. Features MRI classification, AI medical assistant, PDF report generation, role-based dashboards, and clinical analytics.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages