# Building an AI-Powered Carbon Footprint Awareness Platform with Flask, SQLite, and Groq (Llama 3.1)

> Source: <https://dev.to/rohith_cef750793653e3d7bd/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and-groq-llama-31-25m3>
> Published: 2026-06-19 06:42:04+00:00

As climate awareness grows, individuals are looking for actionable ways to reduce their personal carbon footprints. However, most carbon calculators are either too complex or offer generic, unhelpful advice.

To solve this, I built **CarbonWise**—a production-ready Carbon Footprint Awareness Platform. It combines deterministic scientific carbon calculations with real-time, personalized AI reduction strategies using the Groq LLM API.

Here is a technical deep-dive into how I built, secured, and optimized this application for the **PromptWars: Virtual** challenge.

The application is designed to be lightweight, secure, and highly performant, avoiding heavy framework overhead.

```
  ┌──────────────────────────────────────────────────────────┐
  │                       User Browser                       │
  └─────────────┬──────────────────────────────▲─────────────┘
                │ HTTPS (POST / GET)           │ Rendered HTML/CSS
  ┌─────────────▼──────────────────────────────┴─────────────┐
  │                   Flask App (app.py)                     │
  └─────────────┬──────────────┬───────────────▲─────────────┘
                │              │               │
  ┌─────────────▼──────────┐ ┌─▼─────────────┐ │
  │ SQLite DB (carbon.db)  │ │Secure Session │ │
  │   - Users & Logs       │ │  Cookies      │ │
  │   - WAL Mode Enabled   │ └───────────────┘ │
  └────────────────────────┘                   │ Structured JSON Insights
  ┌────────────────────────────────────────────┴─────────────┐
  │                 Groq API (Llama 3.1)                     │
  │     - Model: llama-3.1-8b-instant                        │
  └──────────────────────────────────────────────────────────┘
```

`llama-3.1-8b-instant`

).`carbon_engine.py`

)
To prevent calculation drift, the engine uses fixed conversion factors for logging three main categories:

`0.21`

kg/km), Motorbike (`0.05`

kg/km), Bus (`0.08`

kg/km), and Flight (`0.255`

kg/km).`0.5`

kg/meal) and Non-vegetarian meal (`2.5`

kg/meal).`0.82`

kg/kWh).

``` php
def calculate_co2(activity_type: str, quantity: float) -> float:
    if activity_type not in EMISSION_FACTORS:
        raise ValueError(f"Unknown activity type '{activity_type}'")
    if quantity <= 0:
        raise ValueError("Quantity must be positive")
    return round(EMISSION_FACTORS[activity_type] * quantity, 4)
```

`ai_engine.py`

)
To keep the dashboard fast and prevent redundant external HTTP calls, I implemented a session caching mechanism:

`summary`

, `top_emission_sources`

, `suggestions`

(3–5 tips), `eco_score`

(0–100), and `motivation`

.`/log`

, the cache is invalidated so the dashboard gets fresh insights on the next load.

```
# Check session cache
insights = session.get("ai_insights")
if not insights:
    all_acts = _get_all_activities_7days(user_id)
    insights = get_ai_insights(all_acts, daily_total, category_breakdown)
    session["ai_insights"] = insights
```

To make sure data queries are incredibly fast, I optimized the database schema by introducing a **covering index**:

```
CREATE INDEX IF NOT EXISTS idx_activities_covering 
ON activities(user_id, timestamp, activity_type, co2_kg);
```

With this index in place, queries for the weekly analytics dashboard and category breakdowns are satisfied directly from index pages, bypassing expensive full-table scans. We also optimized category queries to aggregate in a single SQL operation:

```
SELECT 
    CASE 
        WHEN activity_type IN ('car', 'bike', 'bus', 'flight') THEN 'travel'
        WHEN activity_type IN ('veg', 'non_veg') THEN 'food'
        WHEN activity_type IN ('electricity') THEN 'electricity'
    END AS category,
    COALESCE(SUM(co2_kg), 0) AS total
FROM   activities
WHERE  user_id   = ? AND timestamp >= DATE('now', '-6 days')
GROUP  BY category
```

`X-Content-Type-Options: nosniff`

`X-Frame-Options: DENY`

`X-XSS-Protection: 1; mode=block`

`Referrer-Policy: strict-origin-when-cross-origin`

`Content-Security-Policy`

(CSP) restricting assets to `'self'`

and specific secure fonts.`Secure`

, `HttpOnly`

, and `SameSite='Lax'`

flags.`<span role="img" aria-label="...">`

tags for screen-reader compatibility.`.sr-only`

class to visually hide labels while exposing them to accessibility scanners.`<h1>`

header.`4.5:1`

on dark backgrounds.I built a comprehensive test suite in `tests/test_app.py`

containing **47 total assertions** across five key test domains:

`test_carbon_calculation`

`test_api_response`

`test_ai_json_structure`

`test_login`

`test_input_validation`

```
pytest tests/test_app.py -v
# Output: 47 passed in 35.58s
```

Building this platform with **Google Antigravity** shifted my focus from syntax debugging to high-level intent design.

The resulting codebase is performant, accessible, secure, and ready to scale. Let's make the web a greener place! 🌿

*This build is part of my journey with **RohithBuilds**, where I document building real AI applications with zero fluff.*

*If you want to learn how to build production-grade AI systems, check out my courses at rohith-builds.onrender.com.*


