Calculadora de Riesgo de la Alteración en la Salud Mental (Mental Health Risk Calculator) is an AI-powered risk assessment system for mental health alterations. It uses machine learning to analyze clinical and sociodemographic factors, providing healthcare professionals with evidence-based risk predictions without requiring explicit diagnostic labels.
- 🔍 Comprehensive Risk Assessment: Analyzes 18 clinical and sociodemographic features
- 🤖 Machine Learning Powered: Uses Random Forest classification with interpretable results
- 🔐 Secure API: JWT authentication for protected endpoints
- 📊 Detailed Analytics: Risk factor identification and clinical recommendations
- 🚀 Production Ready: Built with FastAPI, PostgreSQL, and modern Python practices
- 📈 Model Retraining: Dynamic model updates as new data becomes available
- ⚡ CI/CD Pipeline: Automated testing, security scanning, and containerized deployment
- 🐳 Docker Support: Multi-stage builds with security best practices
- 🔒 Security Scanning: Automated vulnerability detection with Bandit
- Architecture
- CI/CD Pipeline
- Quick Start
- API Documentation
- Features
- Continuous Learning & Model Retraining
- Model Monitoring
- Development Tools
- New API Endpoints
- Development
- Deployment
- Contributing
- Clinical Context
- License
graph TB
A[Client Application] --> B[FastAPI Server]
B --> C[JWT Auth]
B --> D[Risk Assessment Engine]
D --> E[ML Model]
D --> F[Feature Processor]
B --> G[PostgreSQL Database]
E --> H[Model Storage]
style A fill:#f9f,stroke:#333,stroke-width:2px
style E fill:#9ff,stroke:#333,stroke-width:2px
style G fill:#ff9,stroke:#333,stroke-width:2px
- Backend Framework: FastAPI 0.104.1
- ML Framework: scikit-learn 1.3.2
- Database: PostgreSQL 15+ (SQLite for development)
- Authentication: JWT with python-jose
- Data Validation: Pydantic v2
- ORM: SQLAlchemy 2.0
This project features a comprehensive CI/CD pipeline that ensures code quality, security, and reliable deployments:
- Unit Tests: Core functionality validation
- Integration Tests: End-to-end API testing with PostgreSQL
- Code Coverage: Tracked via Codecov integration
- Type Checking: MyPy static analysis for type safety
- Linting: Black formatter and flake8 for consistent code style
- Security Scanning: Bandit vulnerability detection
- Model Validation: Automated ML model performance checks (AUC > 0.7)
- Synthetic Data Generation: Automated test data creation for CI
- Multi-stage Docker builds with security best practices
- GitHub Container Registry integration
- Non-root container execution for enhanced security
- Health checks and proper signal handling
The pipeline runs automatically on:
- Every push to
mainanddevelopbranches - All pull requests to
main - Builds Docker images only on main branch merges
- ✅ Zero-downtime deployments with containerization
- ✅ Automated quality gates prevent broken code from reaching production
- ✅ Security-first approach with vulnerability scanning and non-root containers
- ✅ ML model validation ensures consistent performance across deployments
- ✅ Professional DevOps practices demonstrating enterprise-ready development
- Python 3.9 or higher
- PostgreSQL 15+ (or use SQLite for development)
- Git
- Clone the repository
git clone https://github.com/yourusername/NeuroRiskLogic.git
cd NeuroRiskLogic- Create virtual environment
python -m venv venv
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate- Install dependencies
pip install -r requirements.txt- Set up environment variables
cp .env.example .env
# Edit .env with your configuration- Initialize the database
# The database tables will be created automatically on first run
python -c "from app.database import init_db; init_db()"- Generate synthetic data and train initial model (Optional)
python scripts/generate_synthetic_data.py
python scripts/train_model.py- Run the application
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000- Access the API
- API Documentation: http://localhost:8000/docs
- ReDoc Documentation: http://localhost:8000/redoc
- Health Check: http://localhost:8000/health
Most endpoints require JWT authentication. To get a token:
curl -X POST "http://localhost:8000/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{"api_key": "your-api-key-here"}'Use the token in subsequent requests:
curl -H "Authorization: Bearer <your-token>" \
http://localhost:8000/api/v1/assessmentsPOST /api/v1/predictMake a risk prediction without storing data:
{
"age": 25,
"gender": "M",
"consanguinity": false,
"family_neuro_history": true,
"seizures_history": false,
"brain_injury_history": false,
"psychiatric_diagnosis": true,
"substance_use": false,
"suicide_ideation": false,
"psychotropic_medication": true,
"birth_complications": false,
"extreme_poverty": false,
"education_access_issues": false,
"healthcare_access": true,
"disability_diagnosis": false,
"social_support_level": "moderate",
"breastfed_infancy": true,
"violence_exposure": false
}Response:
{
"risk_score": 0.72,
"risk_level": "high",
"confidence_score": 0.89,
"risk_factors": [
"Family history of neurological disorders",
"Existing psychiatric diagnosis",
"Currently on psychotropic medication"
],
"protective_factors": [
"Access to healthcare",
"Moderate social support"
],
"recommendations": [
"Immediate comprehensive neurodevelopmental evaluation recommended",
"Genetic counseling may be beneficial",
"Ensure ongoing psychiatric care and medication compliance"
]
}POST /api/v1/assessmentsSubmit and store a full assessment with consent.
GET /api/v1/assessments?limit=10&offset=0Retrieve paginated list of assessments.
GET /api/v1/statsGet comprehensive system statistics and analytics.
The system analyzes 18 evidence-based features:
| Category | Features |
|---|---|
| Clinical-Genetic | Consanguinity, Family neurological history, Seizures, Brain injury, Psychiatric diagnosis, Substance use, Suicide ideation, Psychotropic medication |
| Sociodemographic | Birth complications, Extreme poverty, Education access, Healthcare access, Disability diagnosis, Social support level, Breastfeeding history, Violence exposure |
| Demographics | Age, Gender |
The system includes an automated retraining service that continuously improves model performance:
# Start automated retraining service
python scripts/automated_retraining.py
# Or run once
python scripts/automated_retraining.py --once# Trigger retraining (requires admin token)
curl -X POST http://localhost:8000/api/v1/retrain/start \
-H "Authorization: Bearer <admin-token>" \
-H "Content-Type: application/json" \
-d '{"force": false, "min_samples": 50}'
# Check retraining status
curl -X GET http://localhost:8000/api/v1/retrain/status/<task-id> \
-H "Authorization: Bearer <admin-token>"# Upload new clinical data for retraining
curl -X POST http://localhost:8000/api/v1/retrain/upload-data \
-H "Authorization: Bearer <admin-token>" \
-F "file=@clinical_data.csv"# Evaluate current model
python scripts/evaluate_model.py --plots
# Compare model versions
curl -X GET http://localhost:8000/api/v1/retrain/metrics/comparison?versions=5 \
-H "Authorization: Bearer <admin-token>"# Generate interactive HTML dashboard
python scripts/generate_monitoring_report.py --open
# Dashboard includes:
# - Model performance trends
# - Assessment volume statistics
# - Feature importance analysis
# - Data distribution plotsGET /api/v1/stats- System statisticsGET /api/v1/stats/trends- Assessment trendsGET /api/v1/stats/risk-factors- Risk factor analysis
# Simulate assessments for testing
python scripts/dev_tools.py simulate -n 100 -d 30
# Run system health check
python scripts/dev_tools.py health
# Generate test report
python scripts/dev_tools.py report
# Export data
python scripts/dev_tools.py export -o data_export.csvmake train # Train initial model
make retrain # Run model retraining
make evaluate # Evaluate current model
make monitor # Generate monitoring report
make simulate # Simulate test dataPOST /api/v1/retrain/start- Start retraining taskGET /api/v1/retrain/status/{task_id}- Check task statusGET /api/v1/retrain/history- View retraining historyPOST /api/v1/retrain/upload-data- Upload clinical dataGET /api/v1/retrain/metrics/comparison- Compare model versions
GET /api/v1/stats/trends- Assessment trends over timeGET /api/v1/stats/risk-factors- Risk factor analysis
NeuroRiskLogic/
├── app/
│ ├── models/ # Database and ML models
│ ├── routes/ # API endpoints
│ ├── schemas/ # Pydantic validation
│ ├── utils/ # Utility functions
│ ├── main.py # FastAPI application
│ ├── config.py # Configuration
│ ├── database.py # Database setup
│ └── auth.py # Authentication
├── scripts/
│ ├── generate_synthetic_data.py
│ ├── train_model.py
│ └── evaluate_model.py
├── data/
│ ├── models/ # Trained ML models
│ └── synthetic/ # Generated data
├── tests/ # Test suite
├── docs/ # Additional documentation
└── requirements.txt
# Run all tests
pytest
# Run with coverage
pytest --cov=app --cov-report=html
# Run specific test file
pytest tests/test_predictor.py# Format code
black .
# Lint code
flake8 app/
# Type checking
mypy app/Using Alembic for database migrations:
# Create a new migration
alembic revision --autogenerate -m "Add new column"
# Apply migrations
alembic upgrade head
# Rollback
alembic downgrade -1FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Build and run:
docker build -t neurorisklogic .
docker run -p 8000:8000 --env-file .env neurorisklogic-
Environment Variables
- Set
ENV=production - Use strong
SECRET_KEY - Configure PostgreSQL connection
- Set appropriate CORS origins
- Set
-
Database
- Use PostgreSQL 15+
- Enable connection pooling
- Regular backups
-
Security
- HTTPS only
- Rate limiting
- Input validation
- Regular security updates
-
Monitoring
- Application metrics
- Error tracking (Sentry)
- Performance monitoring
- Health checks
- Heroku: One-click deployment with Procfile
- AWS: EC2 + RDS or ECS + Fargate
- Google Cloud: Cloud Run or App Engine
- Azure: App Service or Container Instances
We welcome contributions! Please see our Contributing Guidelines for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
We use conventional commits:
feat:New featuresfix:Bug fixesdocs:Documentation changesstyle:Code style changesrefactor:Code refactoringtest:Test additions/changeschore:Maintenance tasks
This system implements evidence-based screening for neurodevelopmental disorders based on established clinical risk factors. It is designed to assist healthcare professionals in identifying individuals who may benefit from comprehensive evaluation.
- This is a screening tool, not a diagnostic system
- Results should be interpreted by qualified healthcare professionals
- The system complements, but does not replace, clinical judgment
- All assessments require explicit consent
The risk factors and scoring system are based on:
- Peer-reviewed clinical literature
- Epidemiological studies
- Expert clinical consensus
- WHO guidelines on neurodevelopmental disorders
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI team for the excellent framework
- scikit-learn community for ML tools
- Clinical advisors and domain experts
- Open source contributors
- Author: Samuel Campozano Lopez
- Email: samuelco860@gmail.com
- LinkedIn: Samuel Campozano Lopez