Skip to content

Aaricacoding/EcoTrack-AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

49 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

title EcoTrack AI
emoji 🌿
colorFrom green
colorTo green
sdk docker
pinned false

🌿 EcoTrack AI : Carbon Intelligence Platform

AI-powered carbon footprint calculator with ML predictions, Groq AI insights, anomaly detection, AR product scanner, carbon offset marketplace, and community leaderboard. Hack2Skill Challenge 3 submission.

Python CI Tests FastAPI scikit-learn Tests License: MIT

πŸ”— Live Demo: https://eco-track-ai-three.vercel.app
βš™οΈ Backend API: https://aaricacoding-ecotrack-ai.hf.space


Challenge Requirements Coverage

βœ… Carbon Footprint Calculation: Transport, Home Energy, Diet, and Shopping modules.

βœ… Carbon Reduction Recommendations: Ranked tips sorted by COβ‚‚ impact.

βœ… Machine Learning Forecasting: 6-month predictive trends using Ridge Regression.

βœ… AI-Powered Insights: Groq LLaMA footprint analysis and EcoBot coach.

βœ… Community Features: Global anonymous ranking and footprint distribution.

βœ… Sustainability Awareness: AR product scanner and offset marketplace

βœ… Secure Authentication: Robust JWT lifecycle and password hashing.

βœ… Accessibility Support: Semantic HTML5 and ARIA compliant UI.

βœ… Responsive Design: Mobile-first dashboard and metrics tracking.


What It Does

Feature Detail
4-Step Carbon Wizard Transport Β· Home Energy Β· Diet Β· Shopping β€” under 2 minutes
ML Trend Forecast Polynomial Ridge Regression β€” 6-month carbon trajectory
Anomaly Detection Isolation Forest detects unusual emission spikes in history
AI Insights Groq LLaMA generates personalised narrative footprint analysis
EcoBot AI Coach Multi-turn AI carbon coach β€” knows your exact footprint data
AR Carbon Scanner Point camera at product barcode β€” instant COβ‚‚ footprint overlay
Offset Marketplace 4 verified Indian carbon offset projects with real pricing
Community Leaderboard Anonymous global ranking with footprint distribution chart
Smart Dashboard Donut chart Β· comparison bars vs global/India benchmarks
Ranked Tips Personalised actions sorted by COβ‚‚ impact β€” highest savings first
Secure Accounts JWT + bcrypt authentication with IP rate limiting

Architecture

ecotrack-ai/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ core/        # config Β· security Β· database
β”‚   β”‚   β”œβ”€β”€ models/      # Pydantic schemas Β· SQLAlchemy ORM
β”‚   β”‚   β”œβ”€β”€ routers/     # auth Β· carbon Β· predictions Β· tips Β· insights
β”‚   β”‚   β”œβ”€β”€ services/    # carbon_calculator Β· ml_predictor Β· ai_insights Β· anomaly_detector
β”‚   β”‚   └── main.py      # FastAPI app Β· middleware Β· security headers
β”‚   β”œβ”€β”€ tests/
β”‚   β”‚   β”œβ”€β”€ test_all.py          # Unit tests
β”‚   β”‚   └── test_integration.py  # Integration & API tests
β”‚   β”œβ”€β”€ requirements.txt
β”‚   └── .env.example
└── frontend/
    └── index.html       # Single-file SPA Β· 9 tabs Β· Chart.js Β· ARIA compliant

Quick Start

cd backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
uvicorn app.main:app --reload --port 8000
pytest backend/tests/ -v --tb=short

API Endpoints

Method Endpoint Description
POST /api/auth/register Register new user
POST /api/auth/login Login and receive JWT
GET /api/auth/me Get current user profile
POST /api/carbon/calculate Calculate footprint (authenticated)
POST /api/carbon/calculate/anonymous Calculate footprint (no auth)
GET /api/carbon/history Get user calculation history
POST /api/predictions/forecast 6-month ML forecast
POST /api/tips/personalized Get ranked reduction tips
POST /api/insights/analyze Groq LLaMA footprint analysis
POST /api/insights/anomaly Isolation Forest anomaly detection
POST /api/insights/chat EcoBot multi-turn conversation
GET /api/community/stats Global footprint distribution
GET /api/community/rank/{user_id} Get user community rank
GET /health Health check
GET / Root endpoint

Security

Robust security controls implemented across the API surface:

  • JWT Authentication: Strict token lifecycle management.
  • Authorization Checks: Ownership validation on private resources (e.g., IDOR prevention).
  • bcrypt Password Hashing: Salted and hashed credentials via passlib.
  • Input Validation: Strict Pydantic v2 schemas and payload sanitization.
  • Rate Limiting: IP-based throttles via slowapi on auth, AI, and ML endpoints.
  • Content Security Policy (CSP): default-src 'none' API policy.
  • HSTS Headers: Enforced Strict-Transport-Security.
  • SQL Injection Protection: Pure SQLAlchemy ORM bindings.
  • Environment Secret Management: Startup .env validation block.
  • Global Exception Handling: Stack trace redaction and opaque 500 JSON responses.

Testing : 68 Passing

The backend is backed by a robust, 100% passing test suite designed for stability and evaluation compliance.

  • Unit Tests: Validating calculators, parsers, and utilities.
  • Integration Tests: End-to-end database interactions and auth flows.
  • Security Tests: Verifying bcrypt hashing, JWT tampering, and bounds rejection.
  • ML Tests: Validating deterministic anomaly detection and positive regression forecasts.
  • API Tests: Endpoint contract validation and error handling.
Category Coverage / Focus
TestTransportCalculation Zero input Β· petrol vs EV Β· flights
TestHomeCalculation Solar Β· per-capita scaling
TestDietCalculation Vegan vs omnivore Β· waste multiplier
TestRatingAndPercentile All 5 tiers Β· monotonicity Β· bounds
TestFullFootprint Total integrity Β· valid rating
TestMLPrediction Determinism Β· output length Β· non-negative
TestInputValidation Negative values Β· invalid enums
TestSecurity bcrypt Β· JWT roundtrip Β· tampered token
TestAnomalyDetection Spike detection Β· z-scores Β· determinism
TestInsightSchemas AI request response validation
TestIntegration Full request lifecycle, database state

Accessibility

The frontend SPA implements inclusive design principles:

  • Semantic HTML5: Proper heading hierarchy and landmark elements implemented.
  • ARIA Labels: Interactive elements tagged for screen reader context.
  • Keyboard Navigation: Tab-index support for forms and dashboard tabs.
  • Responsive Design: Mobile-first media queries for seamless mobile/desktop usage.
  • Screen Reader Support: (Standard browser support; advanced custom roles omitted for lightweight design).
  • High Contrast Compatibility: (Pending explicit high-contrast toggle; native OS inversion supported).

Performance Optimizations

  • SQL query limits: Capped row fetches (e.g., limit(1000)) preventing memory exhaustion.
  • Cached configuration via @lru_cache: Single-parse environment variable loading.
  • Optimized SQLAlchemy queries: Minimized N+1 problems via targeted aggregations.
  • Rate-limited AI endpoints: Prevents API quota exhaustion via Groq.
  • Efficient ML inference: Lightweight scikit-learn models executed efficiently.
  • Lightweight frontend architecture: Single-file Vanilla JS SPA minimizes asset payload.

ML Models

Polynomial Ridge Regression (Trend Forecasting)

  • PolynomialFeatures(degree=2) + Ridge(alpha=1.0, random_state=42)
  • Captures realistic reduction curve β€” rapid early gains then plateau
  • Uses real DB history when available, simulated otherwise

Isolation Forest (Anomaly Detection)

  • IsolationForest(n_estimators=100, contamination=0.15, random_state=42)
  • Trains on user personal history β€” not global thresholds
  • Returns per-category z-scores and human-readable explanation

Emission Factors

Category Factor Source
Petrol car 0.192 kg COβ‚‚e/km EPA 2023
EV India grid 0.053 kg COβ‚‚e/km CEA 2023
Electricity India 0.716 kg COβ‚‚e/kWh CEA 2023
Short-haul flight 255 kg COβ‚‚e/trip ICAO
Long-haul flight 1050 kg COβ‚‚e/trip ICAO
Vegan diet 1500 kg COβ‚‚e/yr Poore & Nemecek 2018
Global average 4000 kg COβ‚‚e/yr IPCC AR6
India average 1800 kg COβ‚‚e/yr World Bank

Tech Stack

Layer Technology
Backend FastAPI Β· Python 3.11 Β· Uvicorn
Database SQLAlchemy Β· SQLite
ML scikit-learn Β· numpy
AI Groq LLaMA 3.1 8B
Auth python-jose Β· passlib bcrypt
Frontend Vanilla JS Β· Chart.js Β· BarcodeDetector API
Deployment HuggingFace Spaces Β· Netlify
Testing pytest Β· 62 tests

License

MIT License : Built for Hack2Skill Challenge 3

About

🌿 AI-powered carbon footprint platform with ML predictions, Groq AI insights, anomaly detection and EcoBot coach. Built with FastAPI + scikit-learn.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors