Skip to content

About

Smart Triage oral-disease screening: YOLOv8+SAHI, multi-task DenseNet-169 & ResNet-18 router, FastAPI/Docker deployment with RAG chatbot — basis of a first-author manuscript under review at Frontiers in Big Data

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

title Oral AI Cancer Disease Detection
emoji 🦷
colorFrom blue
colorTo green
sdk docker
pinned false
app_port 7860

🦷 Oral AI: Advanced Disease Detection System

The history of this repository was rewritten on 23 September 2026 to remove personal data; see HISTORY_REWRITE.md.

Paper Python FastAPI PyTorch Docker License

⚠️ Research prototype, not a medical device. Oral AI has not been clinically validated and must not be used for diagnosis.

📄 Published evaluation audit: Char ICJ, Sayed ASA, Ichikawa K, Sayed YMG, Bin Milhan A, Sim DYY and Ramanathan A (2026). From benchmark to user: an end-to-end evaluation audit of an AI-based oral health screening prototype. Frontiers in Big Data 9:1972023. doi:10.3389/fdata.2026.1972023. The audit code and every output file are on the revision-r1 branch (tags v1.1-r1 and v1.1-r1b).

Demo status: the public Hugging Face demo was taken offline in September 2026, after the audit found that the deployed version showed 73% of findings under the wrong condition name. That class-mapping bug is fixed on main: display names now come from the checkpoint's own class registry.


📋 Table of Contents


📖 Overview

Oral AI is a research prototype for screening oral cavity images, built by a student team at the University of Nottingham Malaysia. A multi-model deep learning pipeline gives instant, privacy-focused analysis: images are processed in memory and never stored.

A router model first decides whether an upload is a clinical photo or a histopathology slide, then sends it to the matching specialist model. The published audit (above) measures how well each part, and the whole pipeline, actually performs; the key results are in Model Performance Summary.


🧠 AI Under the Hood: Architecture

Our system uses a "Smart Triage" architecture to chain three specialized Neural Networks together.

👆 Click to see the Full Pipeline Diagram
graph TD
    subgraph User Interaction
        A[User Upload] --> B{Triage Model}
    end

    subgraph "Model C: The Gatekeeper"
        B -- "Clinical Photo" --> C[Model B: Hygiene & Lesions]
        B -- "Histopathology Slide" --> D[Model A: Cancer Analysis]
        B -- "Irrelevant Image" --> E[Reject Upload]
    end

    subgraph "Specialized Analysis"
        C --> F[Generate Clinical Report]
        D --> F
    end

    subgraph "Delivery"
        F --> G[Email to User]
    end

    style A fill:#f9f,stroke:#333,stroke-width:2px,color:#000
    style B fill:#bbf,stroke:#333,stroke-width:2px,color:#000
    style C fill:#bfb,stroke:#333,stroke-width:2px,color:#000
    style D fill:#bfb,stroke:#333,stroke-width:2px,color:#000
    style E fill:#fbb,stroke:#333,stroke-width:2px,color:#000
    style F fill:#ff9,stroke:#333,stroke-width:2px,color:#000
    style G fill:#9ff,stroke:#333,stroke-width:2px,color:#000
Loading

1️⃣ The Triage Gatekeeper (Model C)

  • Architecture: ResNet18 (Transfer Learning)
  • Role: The first line of defense. It classifies input images into two distinct categories:
    • Clinical: Standard RGB photos of the oral cavity (teeth, gums, tongue).
    • Histopathological: Microscopic H&E stained biopsy slides.
  • Why? This routing mechanism ensures that a microscopic model never sees a selfie, and vice versa, preventing false positives and saving computational resources.

2️⃣ The Pathology Expert (Model A)

  • Architecture: Multi-Task DenseNet169 with Custom Regression/Classification Heads.
  • Input: Histopathological (H&E Stained) Microscope Slides.
  • Preprocessing (Macenko Normalization): Pathology slides vary greatly in color depending on the lab's staining process. We use Macenko Normalization to mathematically align the color distribution of every input slide to a "reference" standard before the AI sees it. This makes the model robust to different scanners and staining protocols.
  • 3 Cellular Anomaly Classes (from Roboflow dataset):
    • Mitotic Figures (Regression): Counts cells undergoing mitosis — a key indicator of tumor proliferation.
    • Multiple Nucleoli (Regression): Counts cells with multiple nucleoli — associated with aggressive tumor behavior.
    • Nuclear Hyperchromatism (Regression): Counts cells with abnormally dark nuclei — indicates chromatin abnormalities.
  • Derived Output — TVNT (Binary Classification): Uses the presence/absence of the 3 anomalies above to determine an overall Abnormality Score (Abnormal Tissue vs Normal Tissue). If any of the 3 cellular features are detected at significant levels, the tissue is classified as abnormal.

Audit finding: the TVNT classifier labels every validation image abnormal (105 true positives, 4 false positives, 0 true negatives, 0 false negatives). Its 96.33% accuracy and 100% recall are therefore just the share of abnormal images in the split (105/109): it does not separate normal from abnormal tissue. Validation results, with the audit's corrections, are in the Model Performance Summary.

3️⃣ The Hygiene Specialist (Model B)

  • Architecture: YOLOv8 (You Only Look Once) + SAHI (Slicing Aided Hyper Inference).
  • Input: Smartphone Photos of the Mouth.
  • Advanced Inference (Why SAHI?): Standard object detection models resize images to low resolutions (e.g., 640x640). In a high-res mouth photo, a small cavity might become just 1-2 pixels after resizing, making it impossible to detect. SAHI chops the image into overlapping tiles, runs detection on each tile at full resolution, and then stitches the results back together.
    • SAHI runs only for images at least 640×640 pixels. None of the 1,500 benchmark test images is that large, so the reported detector metrics do not exercise SAHI, and its benefit on full-size phone photos is untested.
  • Detection Classes:
    • Caries (Cavities)
    • Calculus (Tartar/Plaque)
    • Gingivitis (Gum Inflammation)
    • Ulcers
    • Tooth Discoloration
    • Hypodontia (Missing Teeth)

� Model Performance Summary

The numbers below are corrected by the published audit (doi:10.3389/fdata.2026.1972023; outputs on the revision-r1 branch). The per-model metrics describe components on their own splits. End-to-end results describes the product, and the two differ a lot.

Model A: Histopathology Analysis

📊 Click to see Detailed Evaluation Results

Abnormality Detection (TVNT) — Derived from 3 Cellular Anomaly Classes

┌─────────────────────────────────────────────────────────────┐
│  Validation split: 109 images (105 abnormal, 4 normal)      │
│                        Predicted                            │
│                      Normal  Abnormal                       │
│    Actual Normal        0        4                          │
│    Actual Abnormal      0      105                          │
├─────────────────────────────────────────────────────────────┤
│  Every image is predicted abnormal.                         │
│  Accuracy 96.33% = the base rate (105/109), not skill.      │
└─────────────────────────────────────────────────────────────┘
  • The originally reported AUC-ROC of 0.6476 was a single draw: the evaluation code applied training-time augmentation (random flips, rotation, colour jitter) to the validation set. Five re-runs of that path give 0.60–0.79. With a deterministic transform, the same weights give AUC 0.831, but with only 4 normal images that estimate is very uncertain, and the deployed threshold still calls everything abnormal.
  • The count metrics below come from the same augmented evaluation. Deterministic re-evaluation differs slightly (for example, mitotic MAE 0.1352) and is in the audit.

3 Cellular Anomaly Counts (Regression Tasks — Roboflow Dataset)

Feature MAE Exact Match Within ±1
Mitotic Figures 0.1436 cells 93.58% 99.08%
Multiple Nucleoli 2.0272 cells 12.84% 44.04%
Nuclear Hyperchromatism 2.1767 cells 25.69% 55.96%

Model B: Clinical Hygiene Detection

  • Architecture: YOLOv8m, with SAHI for images of 640×640 pixels or more (not exercised by this benchmark; see above)
  • Classes Detected: Caries, Calculus, Gingivitis, Ulcers, Tooth Discoloration, Hypodontia
📊 Click to see Detailed Evaluation Results

Overall Performance (Test Set: 1,500 images)

  • Precision (P): 0.746 (74.6%)
  • Recall (R): 0.728 (72.8%)
  • mAP@50: 0.771 (77.1%)
  • mAP@50-95: 0.401 (40.1%)

Read these with two caveats from the audit:

  • Library version. These figures come from ultralytics 8.3.231, whose AP interpolation overestimates. Ultralytics 8.4.118 gives mAP@50 0.767 and mAP@50-95 0.389 from bit-identical predictions. The library change moves mAP@50-95 by −0.012, more than removing every duplicated test image does.
  • Train–test near-duplicates. 259 of the 1,500 test images (17.3%) are near-duplicates of training images. Removing them changes mAP@50 by +0.001 (95% CI −0.012 to +0.014), so they did not measurably inflate the score. Only 22% of the duplicate pairs carry identical labels, however.

Class-Specific Breakdown

Class Instances Precision Recall mAP@50 mAP@50-95
All Classes 9688 0.746 0.728 0.771 0.401
Calculus 1465 0.667 0.597 0.641 0.281
Caries 1694 0.776 0.792 0.828 0.436
Gingivitis 1544 0.631 0.501 0.555 0.238
Hypodontia 334 0.706 0.740 0.767 0.351
Tooth Discoloration 4153 0.775 0.828 0.878 0.571
Ulcer 498 0.919 0.912 0.958 0.529

Model C: Triage Router

  • Architecture: ResNet18 (Transfer Learning)
  • Task: Binary classification (Clinical vs Histopathological)
  • Purpose: Ensures each image is processed by the correct specialist model
📊 Click to see Detailed Evaluation Results

Routing Performance

  • The training log reports 100% validation accuracy (loss 0.0014), but on the router's own split. Its training data is not in the repository, so overlap with the sets below cannot be ruled out.
  • Audit results at the deployed confidence threshold (0.95):
Set Images Routed correctly Refused as "not a valid image" Sent to the wrong model
Detector test set (clinical photos) 1,500 77.1% 22.9% 0%
Histopathology set 544 75.4% 24.6% 0%
COCO128 (unrelated photos, should be refused) 128 91.4% refused — 8.6% accepted

The router never confuses the two medical domains, but it refuses about a quarter of the system's own valid images.

End-to-end: what a user sees

The audit traced all 1,500 detector test images through the deployed request path (router, image-quality gates, detector and display thresholds).

  • Ulcers are hit hardest. The router refuses 51% of photos that contain an ulcer, so the app reports an ulcer on only 36.5% of ulcer images, against a benchmark recall of 0.91. With the detector alone it would be 71.5%.
  • Valid photos are refused. 22.9% of all test images are refused as "not a valid oral health image" before any analysis.
  • Class-mapping bug (fixed). Before the fix on main, five of six conditions were displayed under another condition's name: 73.4% of displayed findings were wrong, and on 71.6% of images every displayed name was wrong. Names are now read from the checkpoint's own class registry.
  • Not estimable from this benchmark: the test set has no healthy mouths and no patient identifiers, so patient-level sensitivity, specificity in healthy people and predictive values cannot be derived.

�🛠️ Tech Stack & Skills

This project integrates a wide range of modern technologies, demonstrating expertise in full-stack AI development.

Core AI & Deep Learning

  • PyTorch PyTorch: The backbone for training and inference of all neural networks.
  • OpenCV OpenCV: Used for image preprocessing, Macenko normalization, and contour drawing.
  • YOLOv8 Ultralytics YOLOv8: State-of-the-art object detection for clinical images.
  • SAHI (Slicing Aided Hyper Inference): Advanced technique for small object detection in high-resolution images.

Backend & API

  • FastAPI FastAPI: High-performance, asynchronous web framework for serving models.
  • Python Python 3.10: The primary programming language.
  • SQLite SQLite + SQLModel: Lightweight database for user accounts and appointments.
  • JWT JWT Authentication: Secure, stateless token-based authentication.
  • Google Gemini Google Gemini API: Powers the RAG-based medical chatbot.
  • Brevo Brevo (Sendinblue): Transactional email API for delivering PDF reports and appointment notifications.

DevOps & Deployment

  • Docker Docker: Containerization for consistent deployment across environments.
  • Hugging Face Hugging Face Spaces: Cloud hosting platform for the demo.
  • Git Git LFS: Managing large model weights (>100MB).

Frontend

  • HTML5 HTML5 / CSS3: Responsive and clean user interface.
  • JavaScript Vanilla JavaScript: Handles asynchronous API calls and dynamic UI updates.
  • Bootstrap Bootstrap 5: Modern UI components and responsive grid system.
  • FullCalendar FullCalendar.js: Interactive calendar for appointment scheduling.

🤖 AI Chatbot (RAG-Enhanced)

The platform features a context-aware medical assistant powered by Google Gemini Gemma-3.

🔄 Technical Workflow & API Integration

The chatbot doesn't just "guess"; it uses Retrieval-Augmented Generation (RAG) to ground its answers in the model's findings.

  1. Context Retrieval:
    • The system fetches the JSON output from the inference engine (e.g., {"detected": ["Gingivitis"], "confidence": 0.88}).
  2. Prompt Engineering:
    • We construct a dynamic prompt that enforces a "Medical Persona".
    • Template:
      SYSTEM: You are an empathetic oral health assistant.
      CONTEXT: The user's image analysis shows [Gingivitis] with [High] confidence.
      USER QUERY: {user_input}
      GUARDRAILS: Do not diagnose. Suggest professional care.
      
  3. API Call:
    • The constructed prompt is sent to the Gemini Gemma-3 API (generativelanguage.googleapis.com).
    • The response is streamed back to the frontend, providing an instant, conversational explanation of the visual results.
  • Example Interaction:
    • User: "Is this bad?"
    • AI (sees Model B detected 'Gingivitis'): "The analysis detected signs of Gingivitis. While this is common, it indicates gum inflammation. I recommend seeing a dentist for a cleaning..."

✨ Key Features

Feature Description
⚡ Real-time Inference Optimized PyTorch inference allows for analysis in under 3 seconds per image.
🤖 Medical Chatbot Integrated RAG-based Chatbot (powered by Gemini) that knows your specific analysis results and answers follow-up questions contextually.
📄 Smart Reporting Suite Generates professional PDF reports including visual evidence. Emails now deliver both the report and high-res annotated images directly to the user.
🖥️ Interactive Viewport New "Dark Mode" analysis interface with Glassmorphism controls, fullscreen inspection, and dynamic overlay toggles.
📅 Appointment System Full-featured booking system with interactive calendar, doctor selection, and appointment modification capabilities.
🔐 Role-Based Access Secure authentication with distinct Doctor and Patient views, each with tailored functionality.
🌍 Multi-Language UI Complete internationalization supporting English, Malay (Bahasa), Chinese (中文), and Tamil (தமிழ்).
🔔 Smart Notifications Beautiful toast notification system with success, error, warning, and info states for better UX.
🔒 Privacy First HIPAA-compliant design: Images are processed in RAM and wiped immediately after analysis.
🏃 Preventative Care Hub Full-featured daily habit tracker with toggle switches, 7-day history grid, streak counter, achievement level badges, score celebration popups with confetti, rotating daily tips, and motivational messages.
🎯 Action Plan Banner Dynamic alert when Model B detects Gingivitis/Caries. One-click access to AI-generated personalized oral care improvement plans via the RAG chatbot.
🎗️ Oral Cancer Prevention Evidence-based prevention guide covering tobacco, alcohol, diet, and regular dental visits with severity-tagged cards (Critical / Important / Recommended).
🎉 Gamification & Engagement Score celebration popup with animated confetti, star ratings, emoji feedback, and level-based achievements (Starter → Legendary) to encourage consistent oral hygiene.
🎮 Plaque Attack Game Built-in interactive 2D HTML5 Canvas game where users destroy plaque, featuring combo multipliers, procedurally generated Web Audio sounds, particle physics, and ambient visual effects.
☁️ Cloud Native Fully containerized with Docker, ready for serverless deployment.

🏃 Preventative Care Hub

The platform includes a comprehensive Preventative Care Hub — a gamified daily habit tracking system designed to encourage consistent oral hygiene practices.

🦷 Daily Habit Tracker

Users log five key habits each day using intuitive toggle switches:

Habit Type Score Impact
Brushed After Meals ✅ Good +1 if ON
Used Dental Floss ✅ Good +1 if ON
Used Fluoride Toothpaste ✅ Good +1 if ON
Smoked Cigarettes ❌ Bad +1 if OFF
Ate Sugary Snacks ❌ Bad +1 if OFF
  • Lock on Save: Once saved, toggles are locked for the day to prevent tampering — ensuring data integrity.
  • JWT-Protected: All habit data is saved securely via authenticated API endpoints (POST /habits/log, GET /habits/history).

📊 7-Day History Grid

  • Always-Visible Grid: Shows 7 day columns (today + 6 previous days), even if no data exists yet.
  • Color-Coded Scores: Each day displays a score out of 5:
    • 🟢 Excellent (5/5) — Green
    • 🔵 Good (4/5) — Blue
    • 🟡 Average (3/5) — Amber
    • 🔴 Poor (0–2/5) — Red
  • Today Highlight: Current day is visually emphasized with a distinct border.

🔥 Streak Tracking & Achievement Levels

The system tracks consecutive days where the user scores ≥ 3/5, unlocking progressive achievement badges:

Streak Level Icon
0 days Starter 🌱
3+ days Committed 🍃
7+ days Consistent ⭐
14+ days Dedicated 🏅
21+ days Oral Care Pro 👑
30+ days Legendary 💎

🎉 Score Celebration Popup

After saving daily habits, a dramatic full-screen celebration popup appears:

  • Centered Overlay: Fixed-position overlay with backdrop blur and inline style fallbacks for guaranteed rendering.
  • Dynamic Theming: Background gradient and accent color change based on score tier (excellent/good/average/poor).
  • Animated Elements: Bounce-in card, pulsing emoji ring, sequentially-revealed star ratings, and confetti particles for scores ≥ 3.
  • Motivational Messages: Randomized encouraging messages per score level (e.g., "Perfect score! You're a dental superstar!").
  • Dismissible: Close via button, backdrop click, Escape key, or auto-dismiss after 8 seconds.

💡 Daily Oral Health Tips

A rotating card displays a new tip each day, drawn from a curated library of 14 evidence-based oral health insights:

  • "Wait 30 minutes after eating acidic foods before brushing — acid softens enamel temporarily."
  • "Your nighttime brush is the most important — saliva production drops during sleep."
  • "Chewing xylitol gum after meals stimulates saliva and fights cavity-causing bacteria."

🎯 Action Plan Banner

  • Trigger: Automatically appears when Model B detects Gingivitis or Caries in the user's latest scan.
  • One-Click Action: Opens the RAG chatbot with a pre-filled prompt requesting a personalized oral care improvement plan based on the detection results.

🎗️ Oral Cancer Prevention Section

An evidence-based educational guide with severity-tagged cards:

  • 🔴 Critical: Avoid tobacco products, limit alcohol consumption
  • 🟡 Important: Maintain a balanced antioxidant-rich diet
  • 🟢 Recommended: Schedule regular dental check-ups


🎮 Plaque Attack Minigame

To make oral healthcare more engaging, we have built a Plaque Attack Minigame directly into the platform. It is a highly optimized, dependency-free vanilla HTML5 Canvas implementation designed to reward good habits.

🌟 Game Mechanics & Features

  • Physics-based Particles & 3D Shading: Features a procedural 2D rendering engine with 3D gradients and glowing ambient dust effects using globalCompositeOperation.
  • Dynamic Combo Multipliers: Build your score by accurately destroying plaque targets in succession. Misses reset the combo chain.
  • Procedural Web Audio API: No external sound assets required. All sound effects (hits, misses, power-ups) are synthesized dynamically in the browser for an instant, latency-free experience.
  • Glassmorphic UI: Uses modern CSS3 backdrop filters for HUD overlays and popups, matching the main application's dark mode visual language.
  • Responsive Mouse & Touch: Fully playable on desktop and mobile devices.

📅 Appointment Management System

The platform includes a comprehensive appointment scheduling system for healthcare coordination.

🗓️ Interactive Calendar

  • FullCalendar Integration: Beautiful, responsive calendar with month/week views.
  • Visual Indicators: Appointments are displayed with color-coded events.
    • 🔵 Blue: Patient's view (shows doctor name)
    • 🟢 Green: Doctor's view (shows patient name)
  • Click-to-Book: Patients can click any date to view existing appointments or book new ones.

✏️ Appointment Features

Feature Patient Doctor
View Appointments ✅ ✅
Book New Appointment ✅ ❌
Select Preferred Doctor ✅ -
Modify Date & Time ✅ ✅
Update Notes ✅ ✅
Change Status ❌ ✅

📧 Automated Notifications

  • Email Alerts: Both parties receive email notifications via Brevo API when:
    • A new appointment is booked
    • An existing appointment is modified
  • In-App Toasts: Beautiful slide-in notifications confirm actions instantly.

🔐 User Authentication & Roles

The system implements secure, role-based authentication using JWT tokens.

👤 User Roles

Role Capabilities
Patient Book appointments, select doctors, view analysis history, modify own appointments, access AI screening tools
Doctor View patient appointments, update appointment status (confirm/complete/cancel), manage patient notes, access clinical reports
Guest Browse public pages, prompted to login for protected features

🔒 Security Features

  • Password Hashing: BCrypt encryption for secure credential storage.
  • JWT Authentication: Stateless token-based sessions with configurable expiry.
  • Protected Routes: API endpoints validate tokens and enforce role permissions.
  • Session Management: Automatic logout on token expiration with user-friendly prompts.

⚙️ Settings Dashboard

Users can manage their account through a dedicated settings page:

  • Profile Management: Update name and email
  • Password Change: Secure password update with current password verification
  • Notification Preferences: Toggle email notifications for appointments
  • Language Selection: Switch between supported languages
  • Patient Management (Doctors only): View and manage patient information

🌍 Multi-Language Support

The platform is fully internationalized to serve Malaysia's diverse population.

🗣️ Supported Languages

Language Code Coverage
🇬🇧 English en 100%
🇲🇾 Bahasa Melayu ms 100%
🇨🇳 中文 (Chinese) zh 100%
🇮🇳 தமிழ் (Tamil) ta 100%

🔄 Dynamic Translation

  • Instant Switching: Language changes apply immediately without page reload.
  • Persistent Preference: Selected language is saved to localStorage.
  • Complete Coverage: All UI elements translated including:
    • Navigation & menus
    • Form labels & buttons
    • Calendar & appointment system
    • Error messages & notifications
    • Medical analysis reports

🚀 Latest Enhancements (v2.0)

We have recently upgraded the platform with professional-grade UI, reporting capabilities, and a gamified wellness experience:

1. High-Fidelity Visual Reporting

The system now ensures that what you see is what you get.

  • Canvas-to-Image Rendering: We implemented a client-side engine that renders bounding boxes and confidence labels directly onto a high-resolution canvas.
  • Annotated Exports: When a user requests a report, this canvas is converted to a high-quality JPEG and embedded into the PDF and attached to the email. This ensures the doctor/patient sees the exact same detections in the file as they did on the screen.

2. Professional Analysis Viewport

The frontend has been redesigned to mimic professional medical imaging software:

  • Dark Mode Viewport: Reduces eye strain and improves contrast for identifying lesions.
  • Glassmorphism Controls: Floating, semi-transparent controls for toggling heatmaps/detections without obstructing the image.
  • Fullscreen Inspection: Users can now expand the analysis view to examine fine details.

3. Robust Backend Compatibility

  • Format Agnostic: Added intelligent image conversion to handle WebP, PNG, and JPEG uploads seamlessly for PDF generation.
  • Cross-Platform Support: Fixed file permission and pathing issues to ensure smooth operation on both Windows (Localhost) and Linux (Docker/Cloud) environments.

4. Preventative Care Hub & Gamification

A brand-new wellness module designed to drive daily engagement:

  • Habit Tracker: Five toggle-switch habits (brushing, flossing, fluoride toothpaste, no smoking, no sweets) with a daily score out of 5.
  • 7-Day History Grid: Always-visible, color-coded overview of the past week's performance.
  • Streak Counter & Achievement Levels: Tracks consecutive good days and unlocks 6 progressive badges from "Starter" (🌱) to "Legendary" (💎).
  • Score Celebration Popup: Full-screen animated overlay with confetti, star ratings, emoji feedback, dynamic gradients, and motivational messages — displayed on every save.
  • Rotating Daily Tips: 14 curated oral health tips, one shown per day, covering timing, nutrition, and technique.
  • Action Plan Banner: Contextual alert triggered by Model B detections (Gingivitis/Caries), linking directly to the AI chatbot for a personalized care plan.
  • Oral Cancer Prevention Guide: Severity-tagged educational cards (Critical / Important / Recommended) covering tobacco, alcohol, diet, and dental visits.
  • Lock-After-Save: Toggle switches lock after submission to preserve data integrity.
  • JWT-Secured API: POST /habits/log and GET /habits/history endpoints protected by Bearer token authentication.

5. Redesigned Navbar

  • Glassmorphism Navbar: Modern semi-transparent navigation bar with backdrop blur and smooth hover effects.
  • Care Hub Quick Access: Dedicated navbar link for instant access to the Preventative Care Hub from any page.
  • Active State Indicators: Visual highlights for the currently active section.

🛠️ Manual Installation & Usage

Want to run this locally? Follow these steps to compile and run the server on your machine.

Prerequisites

  • Python 3.10+
  • Git (Make sure Git LFS is installed for large model files)

1. Clone the Repository

git clone https://github.com/VanVan120/Oral-Health-Computer-Vision-Model.git
cd Oral-Health-Computer-Vision-Model
git lfs pull  # Crucial: Downloads the actual AI model weights

2. Install Dependencies

We recommend using a virtual environment to keep your system clean.

Windows:

python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt

Mac / Linux:

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

3. Configure Environment Variables

You need a Brevo API key for the email reporting feature to work.

Option A: Create a .env file in the root folder.

Option B: Set it in your terminal:

# Windows PowerShell
$env:BREVO_API_KEY="your_brevo_api_key_here"

# Mac/Linux Terminal
export BREVO_API_KEY="your_brevo_api_key_here"

4. Run the Application

Start the server locally. It will launch at http://localhost:8000.

# Using the Python launcher
python main.py

🐳 Docker Deployment

This project is fully containerized. To run it using Docker without installing Python dependencies manually:

Build the Image

docker build -t oral-ai-backend .

Run the Container

docker run -p 7860:7860 -e BREVO_API_KEY="your_key" oral-ai-backend

Access the app at http://localhost:7860


🧪 Python Unit Testing

The repository includes a comprehensive, 100% passing test suite powered by pytest. The testing suite covers FastAPI endpoint routing, database CRUD operations with an in-memory SQLite pool, safe mock implementations for heavy Deep Learning Model inferences (PyTorch), and secure JWT Role checks.

To execute the test suite locally:

  1. Ensure you have the required testing dependencies installed (pytest, pytest-cov, httpx).
pip install -r requirements.txt
  1. Run tests directly via the pytest module. We use mocked inferences so no actual AI usage limits or huge GPU memory loads are required!
python -m pytest tests/ -v
  1. (Optional) To view a test coverage report:
# First ensure pytest-cov is installed
pip install pytest-cov
python -m pytest tests/ --cov=services --cov=core --cov=app_routers --cov=utils

📂 Project Structure

A quick look at the codebase organization:

📦 Oral-Health-Computer-Vision-Model
 ┣ 📂 core                # ⚙️ Core configs (Database, Auth logic, Models)
 ┃  ┣ 📜 auth_core.py     # 🔐 JWT and Password Hashing
 ┃  ┣ 📜 database.py      # 💾 SQLite Engine & Connectors
 ┃  ┗ 📜 models.py        # 📋 SQLModel Schemas (User, Appointment, HabitLog)
 ┣ 📂 database            # 📁 Local SQLite Database Storage
 ┣ 📂 ml_models           # 🧠 Deep Learning Models Directory
 ┃  ┣ 📂 model_a          # 🧬 Pathology Model (DenseNet/ResNet)
 ┃  ┣ 📂 model_b          # 🦷 Hygiene Model (YOLOv8)
 ┃  ┗ 📂 model_triage     # 🛡️ Router Model (ResNet18)
 ┣ 📂 services            # 🛣️ FastAPI Routers and Business Logic
 ┃  ┣ 📜 appointment_service.py # 📅 Appointment CRUD APIs
 ┃  ┣ 📜 auth_service.py        # 🚪 Authentication Endpoints
 ┃  ┣ 📜 chat_service.py        # 🤖 AI Chatbot Logic (RAG + Guidelines)
 ┃  ┣ 📜 habits_service.py      # 🏃 Daily Habit Tracking API
 ┃  ┗ 📜 report_service.py      # 📄 PDF Generation & Email Delivery
 ┣ 📂 static              # 🎨 Frontend (HTML, CSS, JS)
 ┃  ┣ 📂 css              #    Stylesheets & animations
 ┃  ┣ 📂 html/views       #    Page templates (home, login, settings...)
 ┃  ┗ 📂 js               #    UI handlers & language translations
 ┣ 📂 tests               # 🧪 PyTest Suite (Mocks, Services, DB testing)
 ┣ 📂 utils               # 🛠️ Helper Utilities (Inference processing)
 ┣ 📜 main.py             # ⚡ FastAPI Application Entry Point
 ┣ 📜 Dockerfile          # 🐳 Container Configuration
 ┗ 📜 requirements.txt    # 📦 Python Dependencies

🤝 Contact & Support

Developed for SEGP - Multi-task Deep Learning for Quantifying Key Histopathological Features in Oral Cancer.

Disclaimer: This tool is for educational and assistive purposes only. It does not replace professional medical advice.

About

Smart Triage oral-disease screening: YOLOv8+SAHI, multi-task DenseNet-169 & ResNet-18 router, FastAPI/Docker deployment with RAG chatbot — basis of a first-author manuscript under review at Frontiers in Big Data

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages