{"slug": "building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and", "title": "Building an AI-Powered Carbon Footprint Awareness Platform with Flask, SQLite, and Groq (Llama 3.1)", "summary": "A developer built CarbonWise, a carbon footprint awareness platform using Flask, SQLite, and the Groq LLM API (Llama 3.1). The platform combines deterministic carbon calculations with personalized AI reduction strategies, and features session caching, database optimization, and security headers for production readiness.", "body_md": "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.\n\nTo 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.\n\nHere is a technical deep-dive into how I built, secured, and optimized this application for the **PromptWars: Virtual** challenge.\n\nThe application is designed to be lightweight, secure, and highly performant, avoiding heavy framework overhead.\n\n```\n  ┌──────────────────────────────────────────────────────────┐\n  │                       User Browser                       │\n  └─────────────┬──────────────────────────────▲─────────────┘\n                │ HTTPS (POST / GET)           │ Rendered HTML/CSS\n  ┌─────────────▼──────────────────────────────┴─────────────┐\n  │                   Flask App (app.py)                     │\n  └─────────────┬──────────────┬───────────────▲─────────────┘\n                │              │               │\n  ┌─────────────▼──────────┐ ┌─▼─────────────┐ │\n  │ SQLite DB (carbon.db)  │ │Secure Session │ │\n  │   - Users & Logs       │ │  Cookies      │ │\n  │   - WAL Mode Enabled   │ └───────────────┘ │\n  └────────────────────────┘                   │ Structured JSON Insights\n  ┌────────────────────────────────────────────┴─────────────┐\n  │                 Groq API (Llama 3.1)                     │\n  │     - Model: llama-3.1-8b-instant                        │\n  └──────────────────────────────────────────────────────────┘\n```\n\n`llama-3.1-8b-instant`\n\n).`carbon_engine.py`\n\n)\nTo prevent calculation drift, the engine uses fixed conversion factors for logging three main categories:\n\n`0.21`\n\nkg/km), Motorbike (`0.05`\n\nkg/km), Bus (`0.08`\n\nkg/km), and Flight (`0.255`\n\nkg/km).`0.5`\n\nkg/meal) and Non-vegetarian meal (`2.5`\n\nkg/meal).`0.82`\n\nkg/kWh).\n\n``` php\ndef calculate_co2(activity_type: str, quantity: float) -> float:\n    if activity_type not in EMISSION_FACTORS:\n        raise ValueError(f\"Unknown activity type '{activity_type}'\")\n    if quantity <= 0:\n        raise ValueError(\"Quantity must be positive\")\n    return round(EMISSION_FACTORS[activity_type] * quantity, 4)\n```\n\n`ai_engine.py`\n\n)\nTo keep the dashboard fast and prevent redundant external HTTP calls, I implemented a session caching mechanism:\n\n`summary`\n\n, `top_emission_sources`\n\n, `suggestions`\n\n(3–5 tips), `eco_score`\n\n(0–100), and `motivation`\n\n.`/log`\n\n, the cache is invalidated so the dashboard gets fresh insights on the next load.\n\n```\n# Check session cache\ninsights = session.get(\"ai_insights\")\nif not insights:\n    all_acts = _get_all_activities_7days(user_id)\n    insights = get_ai_insights(all_acts, daily_total, category_breakdown)\n    session[\"ai_insights\"] = insights\n```\n\nTo make sure data queries are incredibly fast, I optimized the database schema by introducing a **covering index**:\n\n```\nCREATE INDEX IF NOT EXISTS idx_activities_covering \nON activities(user_id, timestamp, activity_type, co2_kg);\n```\n\nWith 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:\n\n```\nSELECT \n    CASE \n        WHEN activity_type IN ('car', 'bike', 'bus', 'flight') THEN 'travel'\n        WHEN activity_type IN ('veg', 'non_veg') THEN 'food'\n        WHEN activity_type IN ('electricity') THEN 'electricity'\n    END AS category,\n    COALESCE(SUM(co2_kg), 0) AS total\nFROM   activities\nWHERE  user_id   = ? AND timestamp >= DATE('now', '-6 days')\nGROUP  BY category\n```\n\n`X-Content-Type-Options: nosniff`\n\n`X-Frame-Options: DENY`\n\n`X-XSS-Protection: 1; mode=block`\n\n`Referrer-Policy: strict-origin-when-cross-origin`\n\n`Content-Security-Policy`\n\n(CSP) restricting assets to `'self'`\n\nand specific secure fonts.`Secure`\n\n, `HttpOnly`\n\n, and `SameSite='Lax'`\n\nflags.`<span role=\"img\" aria-label=\"...\">`\n\ntags for screen-reader compatibility.`.sr-only`\n\nclass to visually hide labels while exposing them to accessibility scanners.`<h1>`\n\nheader.`4.5:1`\n\non dark backgrounds.I built a comprehensive test suite in `tests/test_app.py`\n\ncontaining **47 total assertions** across five key test domains:\n\n`test_carbon_calculation`\n\n`test_api_response`\n\n`test_ai_json_structure`\n\n`test_login`\n\n`test_input_validation`\n\n```\npytest tests/test_app.py -v\n# Output: 47 passed in 35.58s\n```\n\nBuilding this platform with **Google Antigravity** shifted my focus from syntax debugging to high-level intent design.\n\nThe resulting codebase is performant, accessible, secure, and ready to scale. Let's make the web a greener place! 🌿\n\n*This build is part of my journey with **RohithBuilds**, where I document building real AI applications with zero fluff.*\n\n*If you want to learn how to build production-grade AI systems, check out my courses at rohith-builds.onrender.com.*\n\n", "url": "https://wpnews.pro/news/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and", "canonical_source": "https://dev.to/rohith_cef750793653e3d7bd/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and-groq-llama-31-25m3", "published_at": "2026-06-19 06:42:04+00:00", "updated_at": "2026-06-19 07:00:05.281716+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-products", "developer-tools"], "entities": ["CarbonWise", "Flask", "SQLite", "Groq", "Llama 3.1", "PromptWars: Virtual"], "alternates": {"html": "https://wpnews.pro/news/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and", "markdown": "https://wpnews.pro/news/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and.md", "text": "https://wpnews.pro/news/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and.txt", "jsonld": "https://wpnews.pro/news/building-an-ai-powered-carbon-footprint-awareness-platform-with-flask-sqlite-and.jsonld"}}