Anevia is an innovative healthcare solution that uses AI-powered image analysis to detect potential anemia through eye conjunctiva scans. This repository contains the backend API that powers the Anevia platform.
- Overview
- Features
- Tech Stack
- API Documentation
- Prerequisites
- Database Schema
- Authentication System
- Chat System
- Local Development Setup
- AWS EC2 Deployment
- License
Anevia's backend provides a robust API for processing eye conjunctiva images to detect potential anemia. The system uses a two-step AI model approach:
- Eye Region Extraction: Identifies and crops the conjunctiva region from uploaded eye images
- Anemia Analysis: Analyzes the extracted conjunctiva to determine potential anemia indicators
The backend also handles user authentication, profile management, scan history storage, and provides an AI-powered chat assistant.
-
AI-Powered Image Analysis:
- Upload and process eye conjunctiva images
- Two-step AI processing pipeline
- Accurate anemia detection from conjunctiva analysis
-
User Management:
- Secure authentication with Firebase
- Multiple authentication providers (Email/Password, Google, and GitHub)
- Provider linking capabilities
- Comprehensive user profile management
-
Data Storage:
- Efficient PostgreSQL database integration
- Secure storage of scan results and user data
- Image file management
-
AI Chat Assistant (ChatVia):
- Integrates with Google Gemini model
- Initiates chat sessions based on scan data
- Provides health advice related to anemia
- Manages chat history for users
-
RESTful API:
- Well-documented endpoints
- Token-based authentication
- Comprehensive error handling
- Backend: Node.js with Hapi.js framework
- Database: PostgreSQL
- Authentication: Firebase Admin SDK
- AI Model: Google Gemini API
- Image Processing: Custom AI models
- Unique IDs: UUID for generating identifiers
- Documentation: Custom HTML/CSS/JS documentation
For comprehensive API documentation, visit:
The documentation includes:
- Detailed endpoint descriptions
- Request/response formats
- Authentication requirements
- Example usage
- Node.js (v14 or higher)
- PostgreSQL database
- Firebase project with Authentication enabled
- Google Cloud Project with Gemini API enabled and API Key
- Storage space for image files
Important: Before creating tables, make sure to connect to the anevia_db database using
\c anevia_dbin the psql shell or by specifying the database when connecting:psql -U postgres -d anevia_db. After creating tables, grant all necessary privileges to your database user.
CREATE TABLE scans (
scan_id VARCHAR(10) PRIMARY KEY,
photo_url VARCHAR(50) NOT NULL,
scan_result BOOLEAN NOT NULL,
scan_date TIMESTAMP NOT NULL
);CREATE TABLE users (
uid VARCHAR(50) PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(50),
photo_url VARCHAR(100) DEFAULT '/profiles/default-profile.jpg',
birthdate DATE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);CREATE TABLE chat_sessions (
session_id VARCHAR(50) PRIMARY KEY,
user_id VARCHAR(50) REFERENCES users(uid),
title TEXT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);CREATE TABLE chats (
chat_id SERIAL PRIMARY KEY,
session_id VARCHAR(50) REFERENCES chat_sessions(session_id),
sender VARCHAR(10) CHECK (sender IN ('user', 'ai')),
message TEXT,
photo_url VARCHAR(255),
timestamp TIMESTAMP DEFAULT NOW(),
type VARCHAR(10) DEFAULT 'text'
);After creating tables, ensure your database user has all necessary privileges:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO anevia_admin;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO anevia_admin;Anevia uses Firebase Authentication for secure user management:
-
Multiple Sign-in Methods:
- Email/Password authentication
- Google OAuth integration
- GitHub authentication
-
Account Management:
- Provider linking (connect multiple auth methods to one account)
- Password reset functionality
- Profile updates
- Account deletion (both from Firebase and PostgreSQL)
-
Security:
- Token-based authentication
- Secure password handling
- Token verification and refresh
- User authenticates with Firebase on the frontend
- Firebase issues an ID token
- Frontend sends token to backend's
/auth/verifyendpoint - Backend verifies token with Firebase Admin SDK
- Backend creates or retrieves user from PostgreSQL database
- User profile data is returned to frontend
- Frontend stores token for authenticated requests
- Token refresh is handled automatically (Firebase tokens expire after 1 hour)
For detailed implementation guidance and code examples, refer to the API documentation.
The Anevia backend integrates with Google Gemini to provide an AI-powered chat assistant (ChatVia!) for users to get health advice related to anemia.
-
AI-Powered Conversations:
- Utilizes Google Gemini model for natural language understanding and generation.
- Provides advice based on scan results and user queries.
-
Session Management:
- Creates new chat sessions linked to user and scan data.
- Maintains chat history within sessions.
-
Safety Handling:
- Configured to handle content safety filters (though filters can be disabled for specific use cases).
POST /api/chats: Start a new chat session with ChatVia! based on scan data.POST /api/chats/messages: Send a message within an existing chat session and get AI response.GET /api/chats/{userId}: Retrieve all chat sessions for a specific user.GET /api/chats/{userId}/{sessionId}: Retrieve all messages within a specific chat session (with user ownership verification).
-
Clone the repository:
git clone https://github.com/Chhrone/anevia-backend.git cd anevia-backend -
Install dependencies:
npm install
-
Create a PostgreSQL database and user:
CREATE DATABASE anevia_db; CREATE USER anevia_admin WITH ENCRYPTED PASSWORD '<your_secure_password>'; GRANT ALL PRIVILEGES ON DATABASE anevia_db TO anevia_admin;
-
Connect to the database and create the required tables:
# Connect to the anevia_db database psql -U postgres -d anevia_db # Or if you're already in the psql shell \c anevia_db
Then create the tables using the schema definitions provided in the Database Schema section:
-- Scans table CREATE TABLE scans ( scan_id VARCHAR(10) PRIMARY KEY, photo_url VARCHAR(50) NOT NULL, scan_result BOOLEAN NOT NULL, scan_date TIMESTAMP NOT NULL ); -- Users table CREATE TABLE users ( uid VARCHAR(50) PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) NOT NULL UNIQUE, password VARCHAR(50), photo_url VARCHAR(100) DEFAULT '/profiles/default-profile.jpg', birthdate DATE, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); -- Chat Sessions table CREATE TABLE chat_sessions ( session_id VARCHAR(50) PRIMARY KEY, user_id VARCHAR(50) REFERENCES users(uid), title TEXT, created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW() ); -- Chats table CREATE TABLE chats ( chat_id SERIAL PRIMARY KEY, session_id VARCHAR(50) REFERENCES chat_sessions(session_id), sender VARCHAR(10) CHECK (sender IN ('user', 'ai')), message TEXT, photo_url VARCHAR(255), timestamp TIMESTAMP DEFAULT NOW(), type VARCHAR(10) DEFAULT 'text' ); -- Ensure the anevia_admin user has all necessary privileges GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO anevia_admin; GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO anevia_admin;
-
Set up Firebase Authentication:
- Create a Firebase project at Firebase Console
- Enable Email/Password, Google, and GitHub authentication providers
- Generate a service account key from Project Settings > Service Accounts
- Download the service account key JSON file
-
Set up Google Gemini API:
- Create a Google Cloud Project and enable the Gemini API.
- Generate an API Key for the Gemini API.
-
Configure environment variables:
cp .env.example .env
-
Update your
.envfile with your specific configuration:# Server Configuration PORT=5000 HOST=localhost # PostgreSQL Configuration PGUSER=anevia_admin PGHOST=localhost PGPASSWORD=your_secure_password PGDATABASE=anevia_db PGPORT=5432 # Firebase Configuration FIREBASE_PROJECT_ID=your-project-id FIREBASE_CLIENT_EMAIL=your-client-email@your-project-id.iam.gserviceaccount.com FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYour Private Key\n-----END PRIVATE KEY-----\n" # Google Gemini API Configuration GEMINI_API_KEY=your_gemini_api_key -
Create required directories:
mkdir -p public/images/scans mkdir -p public/images/conjunctivas mkdir -p public/images/profiles
-
Start the development server:
npm run dev
-
Access the API documentation at http://localhost:5000
-
Launch an EC2 instance:
- Amazon Linux 2 or Ubuntu recommended
- Ensure security groups allow inbound traffic on port 5000 (or your configured port)
-
Set up the environment:
# Install Node.js curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash - sudo apt-get install -y nodejs # Install PostgreSQL sudo apt-get install -y postgresql postgresql-contrib
-
Clone the repository:
git clone https://github.com/Chhrone/anevia-backend.git cd anevia-backend -
Set up the database:
- Follow steps 3-4 from the Local Development Setup section
- Make sure to connect to the anevia_db database before creating tables
- Ensure the database user has all necessary privileges on tables and sequences
-
Configure Firebase following step 5 from the Local Development Setup section
-
Configure Google Gemini API following step 6 from the Local Development Setup section
-
Install dependencies and create directories:
npm install mkdir -p public/images/scans public/images/conjunctivas public/images/profiles
-
Configure environment:
cp .env.example .env nano .env # Edit with your production values -
Use PM2 for process management:
sudo npm install -g pm2 pm2 start server.js --name "anevia-backend" pm2 save pm2 startup
Note: This script assumes you already have a PostgreSQL database set up on your EC2 instance with the required tables.
-
Clone and prepare:
git clone https://github.com/Chhrone/anevia-backend.git cd anevia-backend chmod +x deploy.sh -
Run the deployment script:
./deploy.sh
-
Follow the prompts to configure your environment:
- Database connection details
- Server port configuration
- Optional Nginx reverse proxy setup
- Optional SSL configuration with Let's Encrypt
The deployment script can automatically:
- Install and configure Nginx as a reverse proxy
- Set up SSL certificates with Let's Encrypt
- Configure proper headers and proxy settings
- Enable the site and restart services
For a production-ready deployment, consider:
-
Domain and HTTPS:
- Register a domain with AWS Route 53 or another provider
- Set up HTTPS using Let's Encrypt
- Configure Nginx as a reverse proxy
-
Monitoring and Logging:
- Set up PM2 monitoring (
pm2 monitor) - Configure application logging
- Set up AWS CloudWatch alarms
- Set up PM2 monitoring (
-
Backup Strategy:
- Regular PostgreSQL database backups
- Image file backups
- Environment configuration backups
ISC
Visit our API documentation at https://server.anevia.my.id
Β© 2025 Anevia - Eye Conjunctiva Scanning System for Anemia Detection