Skip to content

Repository files navigation

🌍 SROS – Sustainable Route Optimization System

Smart routing that calculates emissions in real-time and suggests the greenest travel options for Indian cities.

SROS is a full-stack web application that helps users plan eco-friendly trips by calculating COβ‚‚ emissions for different vehicle types and routes, optimizing for speed, balance, or sustainability.


✨ Features

  • Real-time Emission Calculation: Displays COβ‚‚ emissions (in grams) for petrol, diesel, electric, CNG, and public transport options
  • Multi-layer Route Optimization: Offers 3 route variantsβ€”fastest, balanced, and greenestβ€”using OpenRouteService (ORS) API
  • Intelligent Caching: Redis β†’ SQLite β†’ ORS API fallback for fast geocoding and directions
  • User Authentication: JWT-based login/signup with secure password hashing (bcrypt)
  • Achievement System: Gamification with badges for eco-friendly travel milestones
  • Trip Tracking: Store and analyze historical trips with emission stats
  • Rate Limiting & CORS: Production-ready API security with request throttling
  • Admin Dashboard: Real-time user statistics and trip analytics
  • Responsive UI: HTML templates for desktop and mobile browsers

πŸ› οΈ Tech Stack

Backend

  • Framework: Flask 3.0+ with SQLAlchemy ORM
  • Authentication: Flask-JWT-Extended (JWT tokens)
  • Database: SQLite (development) / PostgreSQL (production)
  • Caching: Redis with Celery for async tasks
  • API: OpenRouteService for real routing & geocoding
  • AI: Google Generative AI (Gemini) for insights
  • Security: bcrypt (password hashing), Flask-Limiter (rate limiting), Flask-CORS

Frontend

  • Jinja2 templates (server-side rendering)
  • HTML/CSS/JavaScript (no heavy JS frameworks)
  • Responsive design for all devices

Geospatial & Math

  • NumPy, Pandas, SciPy for calculations
  • NetworkX for graph optimization
  • GeoPy for coordinate operations
  • Custom geocoding cache (SQLite)

DevOps

  • Python 3.11+
  • Gunicorn + Railway deployment (see Procfile and railway.toml)
  • Alembic for database migrations

πŸ“‹ Installation

Prerequisites

  • Python 3.11+ (check: python --version)
  • pip (usually bundled with Python)

Step 1: Clone the Repository

cd "C:\Users\YourUsername\path\to\SROS-main"

Step 2: Create & Activate Virtual Environment

# Create venv
python -m venv venv

# Activate (Windows)
venv\Scripts\activate

# Activate (macOS/Linux)
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

Step 4: Set Up Environment Variables

Copy .env.example to .env and configure:

# Generate a strong SECRET_KEY and JWT_SECRET_KEY
cp .env.example .env

# Edit .env with your settings:
# SECRET_KEY=your-secret-key-here
# JWT_SECRET_KEY=your-jwt-secret-here
# ORS_API_KEY=your-openrouteservice-key
# REDIS_URL=redis://localhost:6379/0
# DATABASE_URL=sqlite:///sros_dev.db  # (dev default)

Step 5: Initialize the Database

set FLASK_APP=app.py
flask db upgrade

Step 6: (Optional) Seed Sample Data

python db_seed.py

Adds 10 sample Indian users and realistic trip data.


πŸš€ Usage

Run the Development Server

python app.py
  • App starts on http://localhost:5000
  • Debug mode auto-reloads on code changes
  • Leave running in a terminalβ€”open the URL in your browser

Health Check

curl http://localhost:5000/health

Returns database and Redis status.

API Endpoints (Examples)

  • Auth: POST /auth/signup, POST /auth/login, POST /auth/logout
  • Routes: GET /api/trips, POST /api/trips, GET /api/stats
  • AI: POST /api/insights (Gemini-powered trip insights)
  • Admin: GET /api/admin/stats (requires JWT token)

Running Tests

pytest

Tests marked with @pytest.mark.unit, @pytest.mark.integration, @pytest.mark.slow.


πŸ“ Project Structure

SROS-main/
β”œβ”€β”€ app.py                  # Flask app factory; entry point
β”œβ”€β”€ config.py              # Config for dev/test/production
β”œβ”€β”€ extensions.py          # Flask extension initialization (db, jwt, cors, etc.)
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ .env.example           # Example environment variables
β”œβ”€β”€ Procfile               # Gunicorn deployment config (Railway)
β”œβ”€β”€ railway.toml           # Railway platform config
β”œβ”€β”€ db_seed.py             # Script to populate sample data
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ db_models.py       # SQLAlchemy models (User, Trip, Achievement, etc.)
β”‚   β”œβ”€β”€ emission_calculator.py  # COβ‚‚ calculation logic for vehicle types
β”‚   β”œβ”€β”€ route_optimizer.py      # Multi-layer geocoding & route optimization
β”‚   └── achievements.py         # Badge/achievement logic
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ api.py             # Core REST API endpoints
β”‚   β”œβ”€β”€ auth.py            # Authentication (signup/login/logout)
β”‚   β”œβ”€β”€ pages.py           # Web pages (dashboard, index)
β”‚   └── ai_services.py     # Google Gemini integration
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ index.html         # Landing page
β”‚   β”œβ”€β”€ dashboard.html     # User dashboard & trip tracker
β”‚   └── (other HTML templates)
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ test_api.py        # API endpoint tests
β”‚   β”œβ”€β”€ test_auth.py       # Authentication tests
β”‚   β”œβ”€β”€ test_emission_calculator.py  # Emission logic tests
β”‚   β”œβ”€β”€ test_route_optimizer.py      # Route optimization tests
β”‚   β”œβ”€β”€ conftest.py        # Pytest fixtures & config
β”‚   └── smoke_test.py      # Basic health checks
β”œβ”€β”€ migrations/            # Alembic migration scripts (auto-generated)
β”œβ”€β”€ instance/              # SQLite DB & runtime files (auto-created)
└── __pycache__/          # Python bytecode (auto-generated, safe to ignore)

πŸ” Environment Variables

Required for local development (see .env.example):

Variable Example Purpose
SECRET_KEY abc123def456... Flask session encryption
JWT_SECRET_KEY xyz789uvw012... JWT token signing
FLASK_ENV development App mode (development/testing/production)
DATABASE_URL sqlite:///sros_dev.db Database connection string
REDIS_URL redis://localhost:6379/0 Redis for caching & JWT blacklist
ORS_API_KEY your-key OpenRouteService API key (get free tier at openrouteservice.org)
ALLOWED_ORIGINS http://localhost:5000 CORS allowed domains

🚒 Deployment

SROS is configured for Railway (see railway.toml and Procfile):

  1. Connect your GitHub repo to Railway
  2. Set environment variables in Railway dashboard
  3. Railway auto-deploys on git push
  4. Uses PostgreSQL (recommended) and Gunicorn server

For other platforms (Heroku, Render, AWS), update Procfile and database URL.


πŸ§ͺ Testing

Run the test suite:

pytest -v                    # All tests
pytest -m unit              # Unit tests only
pytest -m integration       # Integration tests (touch DB)
pytest -m slow              # Slow tests (network calls)

Test coverage:

  • Authentication flows
  • Emission calculations (all vehicle types)
  • Route optimization & caching
  • API validation
  • Database transactions

🎯 Why SROS?

India generates ~200 million tonnes of COβ‚‚ annually from transport, and most travelers are unaware of their environmental impact. SROS empowers users to:

  • See real-time emissions for their journeys
  • Choose greener alternatives without sacrificing speed
  • Earn achievements for sustainable travel
  • Track their carbon footprint over time

πŸ“ API Response Examples

Trip Creation

POST /api/trips

{
  "start_location": "Mumbai, Maharashtra",
  "end_location": "Pune, Maharashtra",
  "vehicle_type": "car_petrol",
  "route_preference": "greenest"
}

Response:

{
  "id": 1,
  "distance_km": 155,
  "co2_grams": 26505,
  "duration_minutes": 165,
  "cost_inr": 1007.5,
  "route_type": "greenest",
  "created_at": "2026-04-18T10:30:00Z"
}

User Stats

GET /api/stats (requires JWT token)

{
  "total_trips": 5,
  "total_distance_km": 650,
  "total_co2_grams": 111225,
  "avg_co2_per_trip": 22245,
  "favorite_vehicle": "car_petrol",
  "achievements": ["eco_warrior", "500km_milestone"]
}

🀝 Contributing

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

πŸ“„ License

This project is open-source. See LICENSE for details (if applicable).


πŸ“§ Support & Questions

For issues, feature requests, or questions:


πŸ† Acknowledgments

  • OpenRouteService: Real-world routing & geocoding
  • Google Gemini: AI-powered trip insights
  • Flask & SQLAlchemy: Backend framework stability
  • Indian Environmental Data: ICCT & EEA emission factors

Happy sustainable routing! 🌱

About

An AI-powered sustainable route optimizer that calculates carbon emissions and suggests eco-friendly travel alternatives using Flask

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages