Skip to content

Procode19/Weather-Forecast-Alert-Application

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🌤️ Weather Forecast & Alert Application

A real-time weather forecasting system with intelligent alerts for rain, heat, wind, and UV conditions
Built with Python, FastAPI, SQLite, and Open-Meteo API

Python FastAPI SQLite License Status


📋 Table of Contents


🎯 Overview

The Weather Forecast & Alert Application is a comprehensive system that:

Fetches real-time weather data from free APIs (Open-Meteo)
Analyzes forecasts to identify risk conditions
Generates intelligent alerts (rain, heat, wind, UV, fog, thunderstorms)
Stores weather history and alert logs
Serves data via REST API
Provides CLI interface for easy interaction
Exports reports as CSV files

Real-World Applications:

  • 🌾 Agriculture - Irrigation planning, frost warnings
  • 🚚 Logistics - Route optimization during storms
  • ⛑️ Event Planning - Rescheduling outdoor events
  • ✈️ Travel - Pre-trip weather checks
  • 🏥 Healthcare - Heat wave preparedness
  • Energy - Solar/wind forecast coordination
  • 🌊 Emergency Management - Storm warnings

✨ Features

Core Features

  • 📍 Multi-location Tracking - Monitor any city worldwide
  • 🔄 Real-time Data - Fresh weather every 3 hours (configurable)
  • 🚨 12+ Alert Rules - Comprehensive condition detection
  • 📊 Hourly & Daily Forecasts - 48h hourly + 7d daily
  • 💾 Historical Storage - Track weather trends
  • 🎮 Simulation Mode - Test without API calls
  • 📋 CSV Reports - Export forecasts for analysis
  • 🌐 REST API - FastAPI with Swagger documentation

Alert Types

Alert Condition Severity
🌧️ Rain Soon Precip prob ≥ 60% ⚠️ Warn
🌧️ Heavy Rain Rainfall ≥ 10mm 🔴 Critical
🔥 Heat Wave Max temp ≥ 40°C 🔴 Critical
🥶 Cold Snap Min temp ≤ 0°C ⚠️ Warn
💨 High Wind Gusts ≥ 15 m/s ⚠️ Warn
☀️ UV High UV index ≥ 8 ⚠️ Warn
🌫️ Fog Visibility < 1 km ⚠️ Warn
⛈️ Thunderstorm Humidity + rain + wind 🔴 Critical
+ 4 more custom rules

🛠 Tech Stack

Backend

  • Python 3.9+ - Core language
  • FastAPI - REST API framework with auto-docs
  • SQLite3 - File-based relational database
  • httpx - Async HTTP client
  • Pydantic - Data validation

APIs & Services

  • Open-Meteo - Free weather API (no key required)
  • Optional: Telegram - Alert notifications
  • Optional: SMTP - Email alerts

Development

  • Git - Version control
  • GitHub - Repository hosting
  • Virtual Environment - Python isolation

🚀 Quick Start

Prerequisites

  • Python 3.8 or higher
  • pip package manager
  • Git (optional)

Installation (5 minutes)

# 1. Clone repository
git clone https://github.com/yourusername/Weather-Forecast-Alert.git
cd Weather-Forecast-Alert

# 2. Create virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# 3. Install dependencies
pip install -r requirements.txt

# 4. Initialize database
python main.py
# Select option 1: Initialize Database

# 5. Add locations to track
python main.py
# Select option 2: Add Location
# Example: Delhi, India (28.7041, 77.1025)

# 6. Fetch real weather data
python main.py
# Select option 3: Fetch Real Weather Data

# 7. View forecast & alerts
python main.py
# Select option 6: Get Forecast & Alerts

📖 Installation

Detailed Setup Guide

Step 1: System Requirements

# Check Python version
python --version  # Should be 3.8+

# Install Git (optional but recommended)
# Visit: https://git-scm.com/downloads

Step 2: Clone Project

# Using Git
git clone https://github.com/yourusername/Weather-Forecast-Alert.git
cd Weather-Forecast-Alert

# OR download ZIP and extract manually

Step 3: Create Virtual Environment

# Windows
python -m venv venv
venv\Scripts\activate

# Mac/Linux
python3 -m venv venv
source venv/bin/activate

# Verify activation (prompt should show (venv))

Step 4: Install Dependencies

pip install --upgrade pip
pip install -r requirements.txt

# Verify installation
python -c "import fastapi; import httpx; print('✓ Installation OK')"

Step 5: Environment Configuration

# Copy template
cp .env.example .env

# Edit .env (optional, defaults work fine)
# Set USE_SIMULATION=true to test without API

Step 6: Initialize Database

python -c "from src.database import init_database; init_database('db/weather.db'); print('✓ Database initialized')"

# Or use interactive menu
python main.py  # Option 1

Step 7: Verify Setup

# Check database exists
ls -la db/weather.db

# Test imports
python -c "from src.ingest import fetch_open_meteo; from src.rules import evaluate; print('✓ All OK')"

💻 Usage

Option 1: Interactive CLI Menu (Recommended)

python main.py

Menu Options:

1. Initialize Database       - Create/reset database
2. Add Location              - Add city to track
3. Fetch Real Weather Data   - Get data from API
4. Load Simulation Scenario  - Generate test data
5. View Locations            - List all tracked cities
6. Get Forecast & Alerts     - View weather predictions
7. Generate Report           - Export to CSV
8. View Alert Scenarios      - Show available test scenarios
9. Exit

Option 2: REST API Server

# Start server
uvicorn api.app:app --reload --port 8000

# Access:
# - API: http://localhost:8000
# - Docs: http://localhost:8000/docs
# - ReDoc: http://localhost:8000/redoc

Option 3: Python Code

from src.database import init_database, query_all
from src.ingest import add_location, fetch_open_meteo, persist_raw, upsert_series
from src.rules import evaluate

# Initialize
init_database("db/weather.db")

# Add location
loc_id = add_location("db/weather.db", "Delhi, India", 28.7041, 77.1025, "Asia/Kolkata")

# Fetch weather
payload = fetch_open_meteo(28.7041, 77.1025, "Asia/Kolkata")
persist_raw("db/weather.db", loc_id, payload, "full")
upsert_series("db/weather.db", loc_id, payload)

# Get forecast
hourly = query_all("db/weather.db", 
    "SELECT * FROM weather_hourly WHERE location_id = ? LIMIT 24", (loc_id,))

# Evaluate alerts
alerts = evaluate(hourly_tuples, daily_tuples)
print(f"Found {len(alerts)} active alerts")

🌐 API Documentation

Base URL

http://localhost:8000

Endpoints

1. Get Locations

GET /locations

Response:

{
  "count": 2,
  "locations": [
    {
      "id": 1,
      "name": "Delhi, India",
      "lat": 28.7041,
      "lon": 77.1025,
      "tz": "Asia/Kolkata"
    }
  ]
}

2. Get Forecast

GET /forecast/{location_id}?hours=24&days=7

Response:

{
  "location": {...},
  "hourly": {
    "count": 24,
    "data": [
      {
        "ts": "2024-01-15T10:00",
        "temp_c": 22.5,
        "humidity": 65.2,
        "wind_ms": 8.2,
        "precip_mm": 0.5,
        "precip_prob": 40.0
      }
    ]
  },
  "daily": {...}
}

3. Get Alerts

GET /alerts/{location_id}

Response:

{
  "location": {...},
  "count": 2,
  "alerts": [
    {
      "code": "RAIN_SOON",
      "label": "Rain likely in next 12 hours",
      "severity": "warn",
      "description": "Precipitation probability >= 60%"
    }
  ]
}

4. Get Current Weather

GET /current/{location_id}

5. Get Statistics

GET /statistics/{location_id}

Full Swagger Docs: http://localhost:8000/docs


📁 Project Structure

Weather-Forecast-Alert-Application/
│
├── 📄 README.md                      # This file
├── 📄 main.py                        # CLI entry point
├── 📄 requirements.txt               # Python dependencies
├── 📄 .env.example                   # Config template
├── 📄 .gitignore                     # Git exclusions
│
├── src/                              # 🐍 Source modules
│   ├── __init__.py
│   ├── ingest.py                     # Fetch from APIs
│   ├── rules.py                      # Alert rules
│   ├── simulation.py                 # Test scenarios
│   └── database.py                   # DB utilities
│
├── api/                              # 🌐 REST API
│   └── app.py                        # FastAPI application
│
├── jobs/                             # ⏰ Background jobs
│   └── refresh.py                    # Scheduled refresh
│
├── db/                               # 💾 Database
│   ├── schema.sql                    # Table definitions
│   └── weather.db                    # SQLite file (created)
│
├── reports/                          # 📋 Generated CSVs
├── outputs/                          # 📁 Generated outputs
├── images/                           # 📸 Screenshots
├── data/                             # 📊 Sample data
└── docs/                             # 📚 Documentation
    └── PROJECT_EXPLANATION.md        # Detailed guide

🚨 Alert Rules

12 Configurable Rules

# Rule Condition Severity
1 RAIN_SOON Precip prob ≥ 60% (12h) ⚠️
2 RAIN_HEAVY Rainfall ≥ 10mm (24h) 🔴
3 HEAT_WAVE Max temp ≥ 40°C 🔴
4 EXTREME_HEAT Max temp ≥ 43°C 🔴
5 COLD_SNAP Min temp ≤ 0°C ⚠️
6 WIND_HIGH Gusts ≥ 15 m/s ⚠️
7 WIND_EXTREME Gusts ≥ 20 m/s 🔴
8 UV_HIGH UV ≥ 8 ⚠️
9 UV_EXTREME UV ≥ 11 🔴
10 HUMIDITY_HIGH Humidity ≥ 80% ℹ️
11 FOG_EXPECTED Visibility < 1 km ⚠️
12 THUNDERSTORM_RISK Humidity + rain + wind 🔴

Severity Levels

  • 🔵 INFO - Informational (nice to know)
  • 🟡 WARN - Action recommended
  • 🔴 CRITICAL - Urgent attention needed

Add Custom Rules

# In src/rules.py
from src.rules import AlertRule

new_rule = AlertRule(
    code="HAIL_RISK",
    label="Hail storm possible",
    description="Temperature drop + high precipitation",
    condition=lambda ctx: (
        ctx.get("tmin_tomorrow", 999) < 5 and
        any((x or 0) >= 70 for x in ctx.get("precip_prob_next_12h", []))
    ),
    severity="critical"
)

🎮 Simulation Mode

Available Scenarios

python main.py
# Option 4: Load Simulation Scenario

Scenarios:

  1. normal_weather - Clear, 25°C, 60% humidity
  2. monsoon_heavy_rain - 25mm rain, 85% probability
  3. heat_wave - 42°C+, dry conditions
  4. cold_snap - -2°C, frost risk
  5. thunderstorm - Severe: 95% rain, 18 m/s winds
  6. foggy_morning - 95% humidity, 0.5km visibility
  7. high_wind_event - 20 m/s winds

Benefits

✓ No API calls needed
✓ Reproducible results
✓ Test specific scenarios
✓ Verify alerts work correctly
✓ Demo without dependencies


📊 Examples

Example 1: Add Location & Fetch Weather

$ python main.py

Select option (1-9): 2

📍 ADD NEW LOCATION

Enter location name (e.g., 'Delhi, India'): New York, USA
Enter latitude: 40.7128
Enter longitude: -74.0060
Enter timezone (default: UTC, e.g., 'Asia/Kolkata'): America/New_York

✓ Location added! (ID=2)

Example 2: View Forecast & Alerts

Select option (1-9): 6

Select location: 1 (Delhi, India)

══════════════════════════════════════════════════════════════════
FORECAST FOR: Delhi, India
══════════════════════════════════════════════════════════════════

📈 NEXT 24 HOURS:
Time                 Temp(°C)     Humidity(%)    Wind(m/s)
──────────────────────────────────────────────────────────────
2024-01-15T10:00     22.5         65.2           8.2
2024-01-15T11:00     23.1         63.8           7.8
...

WEATHER ALERTS (2 active):
══════════════════════════════════════════════════════════════════
⚠️ RAIN_SOON
   Rain likely in next 12 hours
   Severity: WARN

⚠️ HIGH_WIND
   Strong winds: Gusts >= 15 m/s
   Severity: WARN

✓ Report generated: reports/forecast_Delhi_20240115_101530.csv

Example 3: API Request

# Start server
uvicorn api.app:app --reload

# Fetch alerts for location 1
curl http://localhost:8000/alerts/1

# Response:
{
  "location": {"id": 1, "name": "Delhi, India"},
  "count": 2,
  "alerts": [
    {
      "code": "RAIN_SOON",
      "label": "Rain likely in next 12 hours",
      "severity": "warn"
    }
  ]
}

📈 Performance

Database Performance

  • Query Time: < 100ms for typical queries
  • Data Storage: ~5MB for 30 days of data (5 locations)
  • Indexes: Optimized with composite primary keys
  • Scalability: Supports 1000+ locations before optimization needed

API Response Times

  • Locations: < 10ms
  • Forecast: < 50ms
  • Alerts: < 100ms

🔐 Security

Best Practices

API Keys: Never commit .env files
Secrets: Use environment variables
Passwords: Use system keyring
HTTPS: Enable in production
Rate Limiting: Implement API quotas
Input Validation: Pydantic models

Credentials

# ❌ WRONG - Never do this
API_KEY = "abc123xyz"  # Hardcoded

# ✓ RIGHT - Use environment variables
import os
API_KEY = os.getenv("API_KEY")

🤝 Contributing

Contributions welcome! Here's how:

# 1. Fork repository
# 2. Create feature branch
git checkout -b feature/amazing-feature

# 3. Commit changes
git commit -m "Add amazing feature"

# 4. Push to branch
git push origin feature/amazing-feature

# 5. Open Pull Request

Development Checklist

  • Code follows style guide (PEP 8)
  • Tests pass locally
  • No hardcoded secrets
  • Documentation updated
  • Commit messages are clear

🐛 Troubleshooting

Problem: ModuleNotFoundError: No module named 'fastapi'

# Solution: Ensure venv is activated and install dependencies
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install -r requirements.txt

Problem: sqlite3.OperationalError: disk I/O error

# Solution: Check folder permissions and disk space
ls -la db/
chmod 755 db/

Problem: API connection timeout

# Solution: Check internet connection or switch to simulation mode
USE_SIMULATION=true python main.py

📚 Documentation


📊 Statistics

  • Code Lines: ~2000 (excluding docs)
  • Alert Rules: 12 configurable
  • API Endpoints: 8
  • Database Tables: 5
  • Test Scenarios: 7
  • Development Time: ~20-30 hours (including documentation)

🎓 Learning Outcomes

✅ API integration with httpx
✅ Database design with SQLite
✅ REST API development with FastAPI
✅ Rule engine implementation
✅ Alert/notification systems
✅ Data visualization (CSV export)
✅ CLI application design
✅ Environment configuration
✅ Git version control
✅ Production deployment patterns


📞 Support

FAQ

Q: Do I need an API key?
A: No! Open-Meteo is free and doesn't require authentication.

Q: Can I use this commercially?
A: Yes, it's MIT licensed. Just provide attribution.

Q: How often is data updated?
A: Every 3 hours by default (configurable in .env).

Q: Can I deploy on free platforms?
A: Yes! Heroku Free, Render, Railway, or PythonAnywhere.

Contact


📄 License

This project is licensed under the MIT License - see LICENSE file for details.

MIT License

Copyright (c) 2024 [Your Name]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

🙏 Acknowledgments

  • Open-Meteo - Free weather API (https://open-meteo.com/)
  • FastAPI - Modern Python web framework
  • SQLite - Lightweight database engine
  • Community - All contributors and users

🚀 Roadmap

v1.1 (Next)

  • Add more alert rules
  • Improve forecast accuracy
  • Add user preferences

v2.0 (Later)

  • Mobile app (React Native)
  • Multi-provider support
  • Machine learning predictions
  • Real-time notifications

v3.0 (Future)

  • Geospatial queries
  • Calendar integration
  • AQI integration
  • SaaS platform

⭐ If you find this useful, please star the repository!


Last Updated: January 15, 2024
Current Version: 1.0.0
Status: ✅ Production Ready

Weather-Forecast-Alert-Application

🌦️ Developed an AI-Powered Weather Forecast & Alert Application using Python, Streamlit, SQLite, and real-time weather APIs. The system provides live forecasts, smart weather alerts, analytics dashboards, and interactive visualizations with a modern UI for enhanced weather monitoring and decision-making. 🚀

02edfde90e93d56a6977fb9906ebd2ae95a7a3a7

About

🌦️ Developed an AI-Powered Weather Forecast & Alert Application using Python, Streamlit, SQLite, and real-time weather APIs. The system provides live forecasts, smart weather alerts, analytics dashboards, and interactive visualizations with a modern UI for enhanced weather monitoring and decision-making. 🚀

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages