{"id":29504069,"url":"https://github.com/hokagem/mecha-lung","last_synced_at":"2026-04-07T21:31:14.376Z","repository":{"id":304565028,"uuid":"1018145552","full_name":"HokageM/MECHA-LUNG","owner":"HokageM","description":"End-to-end demo for lung-cancer risk prediction: a TypeScript/React client streams synthetic patient data, PostgreSQL stores it with field-level encryption, and a Python FastAPI service decrypts, trains a scikit-learn model, and serves real-time predictions—the server containerized with Docker-Compose.","archived":false,"fork":false,"pushed_at":"2025-07-20T20:20:28.000Z","size":14256,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-28T06:45:36.525Z","etag":null,"topics":["bcrypt","client-server","cors","db","decision-tree-classifier","docker","fastapi","fernet","jwt-authentication","ml","orm","postgresql","python","react","typescript","uvicorn"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HokageM.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-11T17:25:15.000Z","updated_at":"2025-07-20T20:20:32.000Z","dependencies_parsed_at":"2025-07-13T23:44:26.647Z","dependency_job_id":null,"html_url":"https://github.com/HokageM/MECHA-LUNG","commit_stats":null,"previous_names":["hokagem/mecha-lung"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/HokageM/MECHA-LUNG","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HokageM%2FMECHA-LUNG","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HokageM%2FMECHA-LUNG/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HokageM%2FMECHA-LUNG/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HokageM%2FMECHA-LUNG/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HokageM","download_url":"https://codeload.github.com/HokageM/MECHA-LUNG/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HokageM%2FMECHA-LUNG/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31530640,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-07T16:28:08.000Z","status":"ssl_error","status_checked_at":"2026-04-07T16:28:06.951Z","response_time":105,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bcrypt","client-server","cors","db","decision-tree-classifier","docker","fastapi","fernet","jwt-authentication","ml","orm","postgresql","python","react","typescript","uvicorn"],"created_at":"2025-07-15T23:01:43.875Z","updated_at":"2026-04-07T21:31:14.369Z","avatar_url":"https://github.com/HokageM.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MECHA-LUNG\n\n\u003cimg src=\"docs/logo/logo.jpeg\" alt=\"MECHA-LUNG Logo\" width=\"400\" height=\"400\" /\u003e\n\nDemo-Project: **End-to-end lung cancer risk prediction system** with secure doctor authentication, encrypted patient data, and decision-tree predictions.\n\n## 📋 Table of Contents\n\n1. [Overview](#overview)\n3. [Architecture](#architecture)\n4. [Quick Start](#quick-start)\n5. [Setup Guide](#setup-guide)\n6. [Authentication System](#authentication-system)\n7. [Patient Data Encryption](#patient-data-encryption)\n8. [API Documentation](#api-documentation)\n9. [What I Learned](#what-i-learned)\n10. [Technical Stack](#technical-stack)\n\n## 🎯 Overview\n\nMECHA-LUNG is a comprehensive healthcare application that demonstrates:\n\n- 🔐 **Secure JWT Authentication** - Doctor login with encrypted passwords\n- 🏥 **Patient Management** - Add, edit, delete, and view patient records\n- 🔒 **Data Encryption** - Patient names encrypted in database\n- 🤖 **ML Integration** - Automated lung cancer risk assessment\n- 📊 **Risk Visualization** - Clear risk indicators and confidence scores\n- 🌐 **Modern UI** - Responsive React interface\n- 🛡️ **Security First** - HTTPS, CORS, and database protection\n\n## 🏗️ Architecture\n\n```\n┌─────────────────┐    HTTPS    ┌─────────────────┐    SQL    ┌─────────────────┐\n│   React Client  │ ◄─────────► │  FastAPI Server │ ◄───────► │   PostgreSQL    │\n│   (Port 5173)   │             │   (Port 8000)   │           │   (Port 5432)   │\n└─────────────────┘             └─────────────────┘           └─────────────────┘\n         │                               │                              │\n         │                               │                              │\n         ▼                               ▼                              ▼\n   JWT Tokens                    Lung Cancer Predictions        Fernet Encryption\n   localStorage                   Mocked Model                  \n```\n\n## 🚀 Quick Start\n\n### 1. Clone and Setup\n```bash\ngit clone \u003crepository-url\u003e\ncd MECHA-LUNG\n\n# Setup Python environment\npython -m venv .venv\nsource .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\n\n# Install dependencies\npip install -r server/requirements.txt\ncd client \u0026\u0026 npm install \u0026\u0026 cd ..\n```\n\n### 2. Database Setup\n```bash\n# Start PostgreSQL (if using Docker)\ndocker-compose up -d db\n\n# Or use local PostgreSQL instance\n# Create database: lung_db\n# Create user: lung_user with password: supersecret\n```\n\n### 3. Environment Configuration\n```bash\n# Create server/.env file\ncd server\ncat \u003e .env \u003c\u003c 'EOF'\nDATABASE_URL=postgresql://lung_user:supersecret@localhost:5432/lung_db\nSECRET_KEY=your-super-secret-key-change-this-in-production-1234567890abcdef\nACCESS_TOKEN_EXPIRE_MINUTES=30\nENCRYPTION_PASSWORD=mecha-lung-encryption-key-2024\nENCRYPTION_SALT=dV/7eHOI3szZ16tj614JNQ==\nEOF\n```\n\n### 4. Database Setup\n```bash\n# Run complete setup script (creates tables, runs migrations, creates sample doctor)\npython setup.py\n```\n\n### 5. Start Services\n```bash\n# Terminal 1: Start FastAPI server\npython src/main.py\n\n# Terminal 2: Start React client\ncd ../client\nnpm run dev\n```\n\n### 6. Access Application\n- **Frontend**: http://localhost:5173\n- **API Docs**: http://localhost:8000/docs\n- **Login**: Use the sample account created by setup.py (dr_naruto / hokage)\n\n## 📸 Application Screenshots\n\n### Login Screen\n![Login Screen](docs/screenshots/LoginScreen.png)\n*Secure doctor authentication with JWT token management*\n\n### Dashboard\n![Dashboard](docs/screenshots/Dashoard.png)\n*Main application interface with patient management and risk assessment*\n\n### Patient Creation\n![Patient Creation](docs/screenshots/PatientCreation.png)\n*Adding new patients with encrypted name storage and automated risk prediction*\n\n## 🔧 Setup Guide\n\n### Database Configuration\n\n#### Docker\n```yaml\n# docker-compose.yml\nversion: \"3.9\"\nservices:\n  db:\n    image: postgres\n    container_name: mecha_lung_db\n    restart: unless-stopped\n    environment:\n      POSTGRES_DB: lung_db\n      POSTGRES_USER: lung_user\n      POSTGRES_PASSWORD: supersecret\n    ports:\n      - \"5432:5432\"\n    volumes:\n      - pg_data:/var/lib/postgresql/data\nvolumes:\n  pg_data:\n```\n\n### Environment Variables\n\n**Required for server/.env:**\n```bash\n# Database\nDATABASE_URL=postgresql://lung_user:supersecret@localhost:5432/lung_db\n\n# Security\nSECRET_KEY=your-super-secret-key-change-this-in-production-1234567890abcdef\nACCESS_TOKEN_EXPIRE_MINUTES=30\n\n# Encryption (DO NOT CHANGE AFTER SETUP)\nENCRYPTION_PASSWORD=mecha-lung-encryption-key-2024\nENCRYPTION_SALT=dV/7eHOI3szZ16tj614JNQ==\n```\n\n## 🔐 Authentication System\n\n### JWT Token Workflow\n\n#### 1. **Doctor Registration**\n```bash\nPOST /api/doctors/register\n{\n  \"user_name\": \"dr_naruto\",\n  \"password\": \"hokage\"\n}\n```\n\n#### 2. **Doctor Login**\n```bash\nPOST /api/doctors/login\n{\n  \"user_name\": \"dr_naruto\", \n  \"password\": \"hokage\"\n}\n\n# Response:\n{\n  \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n  \"token_type\": \"bearer\",\n  \"user\": {\n    \"id\": 1,\n    \"user_name\": \"dr_naruto\",\n    \"is_active\": true\n  }\n}\n```\n\n#### 3. **Token Usage**\n```bash\n# Include in API requests\nAuthorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\n```\n\n### Security Features\n\n- **Password Hashing**: bcrypt with salt\n- **JWT Tokens**: 30-minute expiration\n- **Stateless Authentication**: No server-side sessions\n- **Token Validation**: Automatic verification on protected endpoints\n\n## 🔒 Patient Data Encryption\n\n### Overview\n\nPatient names are encrypted using **Fernet symmetric encryption** (AES-128) before storage in the database.\n\n### Encryption Flow\n\n```\n1. Doctor enters: \"Naruto Uzumaki\"\n2. Server encrypts: \"Naruto Uzumaki\" → \"Z0FBQUFBQm9j...\"\n3. Database stores: \"Z0FBQUFBQm9j...\"\n4. Server retrieves: \"Z0FBQUFBQm9j...\"\n5. Server decrypts: \"Z0FBQUFBQm9j...\" → \"Naruto Uzumaki\"\n6. Client displays: \"Naruto Uzumaki\"\n```\n\n### Technical Implementation\n\n**Key Generation:**\n```python\ndef get_encryption_key() -\u003e bytes:\n    password = settings.ENCRYPTION_PASSWORD\n    salt = settings.ENCRYPTION_SALT\n    key, _ = generate_key_from_password(password, base64.b64decode(salt))\n    return key\n```\n\n**Database Model:**\n```python\nclass PatientData(Base):\n    name_encrypted = mapped_column(String)\n    \n    def set_encrypted_name(self, name: str):\n        self.name_encrypted = encrypt_text(name)\n    \n    def get_decrypted_name(self) -\u003e str:\n        return decrypt_text(self.name_encrypted)\n```\n\n### Security Benefits\n\n- **Database Breach Protection**: Encrypted names remain unreadable\n- **Transparent to Users**: Doctors see readable names in interface\n\n## 📚 API Documentation\n\n### Authentication Endpoints\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/api/doctors/register` | Register new doctor |\n| POST | `/api/doctors/login` | Doctor login |\n| GET | `/api/doctors/me` | Get current doctor info |\n\n### Patient Management Endpoints\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| POST | `/api/patients` | Create new patient |\n| GET | `/api/patients` | Get all patients |\n| GET | `/api/patients/{id}` | Get specific patient |\n| PUT | `/api/patients/{id}` | Update patient |\n| DELETE | `/api/patients/{id}` | Delete patient |\n\n### Example API Usage\n\n**Create Patient:**\n```bash\ncurl -X POST \"http://localhost:8000/api/patients\" \\\n  -H \"Authorization: Bearer YOUR_TOKEN\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Saske Uchiha\",\n    \"age\": 19,\n    \"smoking\": true,\n    \"coughing\": true,\n    \"shortness_of_breath\": false\n  }'\n```\n\n**Get Patients:**\n```bash\ncurl -X GET \"http://localhost:8000/api/patients\" \\\n  -H \"Authorization: Bearer YOUR_TOKEN\"\n```\n\n## 🎓 What I Learned\n\n### 1. **Authentication \u0026 Security**\n\n**JWT Implementation:**\n- Learned how JWT tokens work (header, payload, signature)\n- Implemented stateless authentication system\n- Understood token expiration and refresh strategies\n\n**Password Hashing**\n- Practiced secure password hashing with bcrypt\n\n**Key Concepts:**\n- **Stateless vs Stateful**: JWT eliminates server-side sessions\n- **Token Security**: Tamper-proof through cryptographic signatures\n- **Password Security**: Hashing vs encryption for different use cases\n\n### 2. **Database Design \u0026 Security**\n\n**Encryption Implementation:**\n- Implemented field-level encryption for sensitive data\n- Understood salt importance for consistent encryption\n\n**Database Concepts:**\n- **ORM Usage**: SQLAlchemy for database operations\n- **Migration Strategies**: Safe schema updates without data loss\n- **Relationship Modeling**: Doctor-Patient relationships\n\n### 3. **API Development**\n\n**FastAPI Framework:**\n- Built RESTful APIs with automatic documentation\n- Implemented dependency injection for authentication\n- Learned request/response modeling with Pydantic\n\n**API Design Patterns:**\n- **CRUD Operations**: Complete patient management\n- **Authentication**: JWT token verification\n- **CORS Configuration**: Cross-origin request handling\n\n### 4. **Frontend Development**\n\n**React with TypeScript:**\n- Built responsive UI components\n- Implemented state management for forms\n\n**User Experience:**\n- **Toggle Switches**: Intuitive boolean input controls\n- **Loading States**: User feedback during operations\n- **Error Handling**: Graceful error display\n- **Responsive Design**: Mobile-friendly interface\n\n### 5. Handling Unbalanced Datasets\n\nDealing with class imbalance is crucial for building robust machine learning models, especially in this [medical dataset](https://www.kaggle.com/datasets/mysarahmadbhat/lung-cancer) where negative cases (e.g., cancer) are rare.\n\n- **Stratified Split:**  \n  Ensures both training and test sets maintain the original class distribution, preventing bias during evaluation.\n\n- **Balanced Accuracy Score:**  \n  - Defined as the arithmetic mean of sensitivity (recall for the positive class) and specificity (recall for the negative class).\n  - For binary classification, this is equivalent to the ROC-AUC score.\n  - Provides a more informative metric than plain accuracy on imbalanced data.\n\n- **SMOTE (Synthetic Minority Over-sampling Technique):**  \n  - Generates artificial examples of the minority class to balance the dataset.\n  - Applied only to the training data to prevent data leakage.\n\n**How SMOTE Works:**\n1. Select a minority-class sample \\( x \\).\n2. Find its \\( k \\) nearest minority-class neighbors.\n3. Randomly choose one of these neighbors \\( x_n \\).\n4. Synthesize a new sample along the line segment between \\( x \\) and \\( x_n \\).\n5. Repeat until the desired number of synthetic samples is reached.\n\n## 🛠️ Technical Stack\n\n### Backend\n- **Framework**: FastAPI (Python)\n- **Database**: PostgreSQL with SQLAlchemy ORM\n- **Authentication**: JWT with python-jose\n- **Encryption**: cryptography (Fernet)\n- **Password Hashing**: bcrypt\n- **Server**: uvicorn\n\n### Frontend\n- **Framework**: React 18 with TypeScript\n- **Build Tool**: Vite\n- **Styling**: Inline styles\n- **HTTP Client**: Fetch API\n\n### Security\n- **Authentication**: JWT tokens\n- **Encryption**: AES-128 (Fernet)\n- **Password Security**: bcrypt hashing\n- **Transport**: HTTPS/TLS\n- **CORS**: Cross-origin resource sharing\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhokagem%2Fmecha-lung","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhokagem%2Fmecha-lung","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhokagem%2Fmecha-lung/lists"}