DEV Community

Salman Ahmad
Salman Ahmad

Posted on

SmogShield-LHR: Banishing Lahore's "Gray Ghost" with Open-Weight AI & Deterministic Health Telemetry

Hacktoberfest Open-Source AI Challenge: Ghost in the Machine Submission 👻🌼

This is a submission for the Hacktoberfest Open-Source AI Challenge Week 4: Ghost in the Machine

What I Built

Every winter in Lahore, Pakistan, the city is haunted by what locals call the "Fifth Season"—or the "Gray Ghost".

Starting late October, a severe meteorological phenomenon known as atmospheric thermal inversion traps industrial emissions, vehicular exhaust, brick kiln smoke, and agricultural stubble burning close to the ground. Cold air blankets the city from above, acting like a lid on a pot. The resulting toxic smog ($\text{PM}{2.5}$ and $\text{PM}{10}$) turns Lahore into one of the most polluted cities on Earth, with AQI levels routinely spiking beyond 400.

Lahore's centuries-old Mughal minarets, parks, and streets dissolve into eerie, ghostly silhouettes. But the real horror is invisible: citizens breathing air so toxic that a standard daily routine equals smoking dozens of cigarettes.

Conventional weather services provide abstract indices like "AQI 295". But for an everyday citizen, numbers like "295" fail to answer critical life questions:

  • How much toxic smoke did I actually inhale on my 45-minute motorbike commute today?
  • When does the thermal inversion layer lift so I can safely commute to university or exercise?
  • When is it safe to open windows for ventilation versus keeping HEPA filters running?
  • How do I warn my non-technical family and elders in their everyday language (Roman Urdu) without sending dry bureaucratic tables?

SmogShield-LHR is an open-source command center and AI-powered decision-support system designed to solve this crisis. It bridges live open telemetry from the Open-Meteo Air Quality API with deterministic mathematical health engines and a fast, open-weight AI intelligence layer (Llama 3.1 8B via Groq) to convert raw atmospheric sensor data into actionable human terms:

  1. Berkeley Earth Cigarette Equivalence: Computes your personal cigarette-smoke intake adjusted for your transit mode and vulnerability.
  2. Algorithmic Safe Commute Windows: Scans the 24-hour diurnal forecast to isolate the 3 cleanest daytime hours (06:00–21:00 PKT) to reschedule travel.
  3. Automated Roman Urdu WhatsApp Alerts: Generates single-asterisk formatted alerts (*Alert*) ready for 1-click clipboard copying into family WhatsApp groups.
  4. Resilient Offline Architecture: Bundled with a verified offline atmospheric sample so the tool continues functioning during network blackouts.

Demo

  • 🌐 Live Interactive Deployment: https://smog-sheild-lhr.vercel.app
  • 💻 Target Viewport: Zero-friction single command center, fully responsive across desktop, tablet, and mobile with dark/light mode support.

One-Click Evaluation Presets for Judges

To test real-world scenarios instantly, the dashboard includes three pre-configured judge presets:

  1. Preset 1 (Critical Exposure — Student Motorbike Commuter):
    • Profile: Johar Town (Riphah Campus), Motorbike Rider (1.8x intake multiplier), 5 hours outside.
    • Outcome: Flags extreme particulate intake ($>1.5$ cigarettes equivalent in hours), warns against morning rush-hour thermal spikes, and shifts travel to the optimal 13:00–15:00 window with a $-59\%$ particulate reduction.
  2. Preset 2 (Vulnerable Demographic — Senior Citizen / Asthma Care):
    • Profile: Mall Road (Civil Lines), Sensitive Group (2.0x vulnerability weight), 2 hours outside.
    • Outcome: Recommends strict morning window sealing, reschedules outdoor walks away from peak morning inversion, and outputs custom ventilation rules.
  3. Preset 3 (Edge-Case Test — Client Validation Boundary):
    • Profile: 15 hours outside (exceeds the 12-hour limit), empty routine.
    • Outcome: Triggers instant client-side validation, blocks submission, and records an audit row with 0 network calls or token expenditure.

Code

The entire codebase is open-source under the MIT License:

System Architecture

flowchart TD
    User["User Profile: Zone + Mode + Hours + Routine"] --> Client["Single-Viewport Command Center<br/>(app/page.tsx)"]
    Client -->|"POST /api/smog (JSON)"| RouteHandler["Route Handler<br/>(app/api/smog/route.ts)"]
    RouteHandler -->|"Validate with Zod"| ZodValidation{"Valid Input?"}
    ZodValidation -->|No| ErrResponse["400 Bad Request<br/>(Formatted Error List)"]
    ZodValidation -->|Yes| OpenMeteoAPI[("Open-Meteo Air Quality REST API<br/>(5s Timeout)")]
    OpenMeteoAPI -.->|"On Timeout / Network Drop"| BundledSample["Bundled Realistic Sample<br/>(lib/offlineSample.ts)"]
    OpenMeteoAPI --> CalcEngine["Deterministic Calculation Engine<br/>(lib/calc.ts)<br/>- Berkeley Earth Cigarettes<br/>- WHO Safety Multiples<br/>- Safe 06:00-21:00 Windows"]
    BundledSample --> CalcEngine
    CalcEngine --> GroqLLM[("Open-Weight AI Inference<br/>llama-3.1-8b-instant on Groq Cloud")]
    GroqLLM --> Normalizer["Post-Processing & Normalization<br/>- Deterministic Risk Band Override<br/>- Math Hallucination Strip<br/>- WhatsApp Single-Asterisk Normalizer"]
    Normalizer -->|"HTTP 200 (SmogResponse)"| Client

How I Built It

1. The Open-Weight AI Intelligence Layer (<8B Parameters)

We wanted an AI engine that was blazing-fast, lightweight, and cost-effective. We integrated Llama 3.1 8B (llama-3.1-8b-instant) via the Groq Cloud API, delivering sub-second inference latencies (~350ms).

The AI layer generates four distinct artifacts:

  • Executive Context: Meteorological analysis of current thermal inversion dynamics in Lahore.
  • Commute Rescheduling Plan: Practical schedule shifts with server-calculated reduction percentages (e.g., "Shift your university commute from 08:00 to 12:30 to avoid peak morning ground-level trapping").
  • Home Ventilation Protocol: Exact clock times for when windows must remain sealed vs. when afternoon solar radiation allows brief cross-ventilation.
  • Roman Urdu WhatsApp Alert: Formatted exclusively with single asterisks (*alert*) for clean, bold rendering in WhatsApp family groups.

2. The Zero-Hallucination Deterministic Engine

One core engineering rule guided this project: Never let an LLM do arithmetic or diagnose medical risk. LLMs are notorious for hallucinating percentages and severity bands.

In SmogShield-LHR, all health calculations are computed deterministically in lib/calc.ts before the AI is invoked:

  • Berkeley Earth Cigarette Equivalence Standard:
    $$\text{Cigarettes Inhaled} = \left(\frac{\text{Mean PM}{2.5}}{22}\right) \times \left(\frac{\text{Hours Outside}}{24}\right) \times \text{Intake Multiplier}$$
    *(Translates $22\ \mu\text{g/m}^3$ of $\text{PM}
    {2.5}$ exposure over 24 hours into the toxic particulate equivalent of smoking 1 cigarette).*

  • Physiological Exposure Multipliers:

    • Motorbike / Yango / Bykea rider (1.8x): Heavy open-air particulate intake through unsealed helmets.
    • Pedestrian / Runner (1.5x): Elevated respiratory ventilation rate during exertion.
    • Car / Sealed Cabin with AC Recirculation (0.6x): Filtered enclosure.
    • Sensitive Group / Elderly / Asthma (2.0x): Elevated biological vulnerability.
  • Algorithmic Safe Window Detection:
    The system scans 24-hour CAMS hourly telemetry between 06:00 and 21:00 PKT, sorting the hours to find the 3 cleanest windows (when solar heating breaks the surface inversion) and the 3 peak hazard spikes (morning and evening traffic + cold ground air).

// Deterministic Cigarette Equivalence Calculation (lib/calc.ts)
export function calcCigarettes(pm25: number, hoursOutside: number, multiplier: number): number {
  if (hoursOutside <= 0 || pm25 <= 0) return 0;
  const raw = (pm25 / 22) * (hoursOutside / 24) * multiplier;
  return Number(raw.toFixed(1));
}
Enter fullscreen mode Exit fullscreen mode

3. Resilient Offline Fallback

During intense winter smog, Lahore frequently experiences telecom drops, ISP degradation, or power cuts. If Open-Meteo fails or takes longer than 5 seconds, SmogShield-LHR automatically falls back to a verified, bundled Lahore hourly telemetry dataset (lib/offlineSample.ts), clearly displaying an OFFLINE SAMPLE badge to the user.


Why Does Open Innovation Matter?

  1. Public Health Tools Must Belong to the Public: When an environmental crisis affects over 14 million citizens in a developing metropolis, life-saving decision tools cannot be locked behind subscription paywalls or closed-source proprietary APIs that can change pricing or revoke access overnight.
  2. Offline & Air-Gapped Autonomy: Open-weight models like Llama 3.1 8B can be deployed locally using Ollama on consumer hardware. During natural disasters or grid failures, open AI combined with local sensor caches means citizens still have an air-quality advisor that runs with the internet turned off.
  3. Cultural Nuance and Local Dialects: Closed proprietary models often generate overly formal, generic translations. Open-weight models allow developers to fine-tune prompts for localized dialects like Roman Urdu ("Bahar smog bohot zyada hai, mask lazmi pehnen"), speaking the exact language families use in daily conversation.
  4. Civic Transparency & Scientific Verifiability: Because SmogShield-LHR is completely open-source (MIT), public health researchers, students at local universities (like Riphah International University), and environmental activists can inspect every line of code, audit the formulas, and adapt the system for other smog-affected cities across South Asia (such as Delhi, Faisalabad, or Gujranwala).

My Agent Session

This project was developed and refined using modern AI agent workflows with Antigravity and DevRelay, following spec-driven development and test-first engineering:

  • Over 140 automated tests in Vitest covering deterministic calculations, EPA AQI band boundaries, coordinate validation, and route handlers.
  • Complete documentation suites including comprehensive requirements, architectural specifications, and judge evaluation guides.

The Spirit of It

Lahore is a city of rich memories—of historic gardens, street chai at dawn, and vibrant open-air bazaars. But each winter, the "Gray Ghost" creeps in like a phantom in the night, stealing visibility, canceling schools, and sending elders and children to respiratory clinics.

In the spirit of Ghost in the Machine and Día de los Muertos, SmogShield-LHR is built to confront that specter. It turns invisible, phantom atmospheric threats into concrete, understandable numbers—empowering everyday students, commuters, and families to protect their health and reclaim their city from the fog.


Prize Categories

  • Overall Open-Source AI Challenge Winner: A complete, production-ready civic health tool powered by open-weight models (<8B parameters) addressing a real-world humanitarian and environmental crisis.
  • Featured Category: Best Use of DigitalOcean / Render: Containerized Next.js 16 full-stack architecture ready for cloud deployment.
  • Open Innovation Highlight: Demonstrates why open-weight models and deterministic code guardrails are essential for high-stakes public health software.

Top comments (0)