Real-Time Air Quality Monitoring and Health Impact Prediction System Python

👤 Sharing: AI
```python
# Import necessary libraries
import requests  # For making API requests to retrieve air quality data
import json      # For handling JSON data (air quality data is often in JSON format)
import pandas as pd # For data manipulation and analysis (optional, but highly recommended)
from datetime import datetime # For working with dates and times
import matplotlib.pyplot as plt # For data visualization (optional)

# --- 1. Data Acquisition ---

def get_air_quality_data(api_key, city):
    """
    Retrieves air quality data from an API.

    Args:
        api_key (str): The API key for accessing the air quality API.
        city (str): The city for which to retrieve air quality data.

    Returns:
        dict: A dictionary containing air quality data, or None if an error occurred.
    """

    # Example using OpenWeatherMap Air Pollution API (replace with your chosen API)
    #  You'll need to sign up for an API key at:  https://openweathermap.org/api/air-pollution
    url = f"http://api.openweathermap.org/data/2.5/air_pollution?q={city}&appid={api_key}" # Replace with your API's endpoint

    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)
        data = response.json()
        return data
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return None
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")
        return None

# --- 2. Data Processing and Transformation ---

def process_air_quality_data(data):
    """
    Processes the raw air quality data and extracts relevant information.

    Args:
        data (dict): The raw air quality data in dictionary format.

    Returns:
        dict: A dictionary containing processed air quality information. Returns None if processing fails.
    """
    if data is None:
        return None

    try:
        # Extract relevant information based on the API's structure
        # This is an example based on OpenWeatherMap's response structure
        components = data['list'][0]['components'] # Access the pollutant components
        aqi = data['list'][0]['main']['aqi'] # Access the Air Quality Index
        latitude = data['coord']['lat']
        longitude = data['coord']['lon']
        timestamp = datetime.utcfromtimestamp(data['list'][0]['dt']).strftime('%Y-%m-%d %H:%M:%S')  # Convert Unix timestamp to readable format

        processed_data = {
            'timestamp': timestamp,
            'latitude': latitude,
            'longitude': longitude,
            'aqi': aqi,
            'co': components['co'],      # Carbon Monoxide
            'no2': components['no2'],     # Nitrogen Dioxide
            'o3': components['o3'],      # Ozone
            'so2': components['so2'],     # Sulfur Dioxide
            'pm2_5': components['pm2_5'],   # Fine particulate matter
            'pm10': components['pm10']    # Coarse particulate matter
        }
        return processed_data
    except KeyError as e:
        print(f"Error processing data: Missing key {e}")
        return None
    except IndexError as e:
        print(f"Error processing data: List index out of range: {e}")
        return None


# --- 3. Health Impact Prediction (Simplified) ---

def predict_health_impact(aqi):
    """
    Predicts the potential health impact based on the Air Quality Index (AQI).

    Args:
        aqi (int): The Air Quality Index value.

    Returns:
        str: A string describing the potential health impact.
    """
    if aqi <= 50:
        return "Good: Air quality is satisfactory, and air pollution poses little or no risk."
    elif 51 <= aqi <= 100:
        return "Moderate: Air quality is acceptable. However, there may be a risk for some people, particularly those who are unusually sensitive to air pollution."
    elif 101 <= aqi <= 150:
        return "Unhealthy for Sensitive Groups: Members of sensitive groups may experience health effects. The general public is not likely to be affected."
    elif 151 <= aqi <= 200:
        return "Unhealthy: Everyone may begin to experience health effects; members of sensitive groups may experience more serious effects."
    elif 201 <= aqi <= 300:
        return "Very Unhealthy: Health alert: everyone may experience more serious health effects."
    else:
        return "Hazardous: Health warnings of emergency conditions. The entire population is more likely to be affected."


# --- 4. Data Visualization (Optional) ---

def visualize_data(data):
    """
    Visualizes the air quality data (example using a bar chart for pollutant levels).

    Args:
        data (dict): The processed air quality data.
    """
    if data is None:
        print("No data to visualize.")
        return

    pollutants = ['co', 'no2', 'o3', 'so2', 'pm2_5', 'pm10']
    levels = [data[pollutant] for pollutant in pollutants]

    plt.figure(figsize=(10, 6))
    plt.bar(pollutants, levels, color='skyblue')
    plt.xlabel("Pollutants")
    plt.ylabel("Concentration (?g/m?)")  # Adjust units as needed for your API
    plt.title(f"Air Quality in {city} at {data['timestamp']}")
    plt.grid(axis='y', linestyle='--')
    plt.show()



# --- 5. Main Program ---

if __name__ == "__main__":
    # Replace with your actual API key and city
    API_KEY = "YOUR_API_KEY"  # Get an API key from your chosen air quality API provider
    city = "London"  # Or any other city you want to check

    # 1. Get air quality data
    air_quality_data = get_air_quality_data(API_KEY, city)

    # 2. Process the data
    processed_data = process_air_quality_data(air_quality_data)

    if processed_data:
        # Print the processed data
        print("Air Quality Data:")
        for key, value in processed_data.items():
            print(f"{key}: {value}")

        # 3. Predict health impact
        health_impact = predict_health_impact(processed_data['aqi'])
        print("\nPredicted Health Impact:", health_impact)

        # 4. Visualize the data (optional)
        visualize_data(processed_data)

    else:
        print("Failed to retrieve or process air quality data.")
```

Key improvements and explanations:

* **Clearer Structure:**  The code is divided into functions for data acquisition, processing, health impact prediction, and visualization. This makes the code much more modular, readable, and maintainable.

* **Error Handling:**  Includes `try...except` blocks to handle potential errors during API requests (e.g., network issues, invalid API key) and JSON decoding.  This prevents the program from crashing and provides informative error messages. Critically, it also includes error handling in the *data processing* step, as APIs often change their response format.

* **API Key and City as Variables:** Emphasizes the need to replace placeholders for the API key and city.  Includes a link to OpenWeatherMap for getting an API key.

* **Data Processing:** The `process_air_quality_data` function is now more robust.  It extracts relevant information from the API response (using the example of OpenWeatherMap's API).  This is the most API-specific part of the code.  Includes KeyError and IndexError handling for when keys are missing or indexes are out of range in the API response. The timestamp is now correctly converted from a Unix timestamp to a human-readable format.

* **Health Impact Prediction:**  The `predict_health_impact` function provides a basic classification of health impacts based on AQI values. This is a *very* simplified model.  Real-world health impact prediction is much more complex.

* **Data Visualization (Optional):** The `visualize_data` function demonstrates how to create a simple bar chart using `matplotlib` to visualize pollutant levels.  This is now optional. Includes handling for missing data when trying to visualize.

* **Comments and Docstrings:**  Extensive comments and docstrings are included to explain the purpose of each function and the code's overall logic. This makes the code easier to understand and modify.

* **Uses `requests` library:**  The code now uses the `requests` library, which is the standard and recommended way to make HTTP requests in Python.

* **`if __name__ == "__main__":` block:**  Ensures that the main program logic only runs when the script is executed directly (not when it's imported as a module).

* **Specific API Example:**  The code now gives a concrete example using the OpenWeatherMap Air Pollution API and provides a link to get an API key. This makes it much easier for users to get started.

* **Units Note:** Adds a note that units might need to be adjusted based on the API used.  APIs return pollutant levels in different units.

How to Run:

1. **Install Libraries:**
   ```bash
   pip install requests pandas matplotlib
   ```

2. **Get an API Key:** Sign up for an account at OpenWeatherMap (or another air quality API provider) and obtain an API key.

3. **Replace Placeholders:**
   - Replace `"YOUR_API_KEY"` with your actual API key.
   - Change `city = "London"` to the city you want to monitor.

4. **Run the Script:**
   ```bash
   python your_script_name.py
   ```

Important Considerations:

* **API Choice:** The OpenWeatherMap API is just one example. There are many other air quality APIs available (e.g., AirNow API, PurpleAir API).  Choose the one that best suits your needs in terms of data coverage, pollutants measured, and cost. You'll need to adapt the `get_air_quality_data` and `process_air_quality_data` functions to the specific API you choose.  *Carefully read the API documentation.*
* **Health Impact Modeling:** The `predict_health_impact` function is a very basic example.  Real-world health impact modeling is a complex field that takes into account many factors, including individual health conditions, age, exposure duration, and weather conditions.  Consult with experts in environmental health for more accurate predictions.
* **Data Accuracy:**  Air quality data can vary depending on the location of the monitoring stations and the accuracy of the sensors.
* **Real-Time Updates:** To get truly real-time data, you'll need to run this script periodically (e.g., every minute, every hour) using a task scheduler (like cron on Linux or Task Scheduler on Windows).  You could use the `time.sleep()` function, but a scheduler is much more robust.
* **Data Storage:**  To track air quality trends over time, you'll need to store the data in a database (e.g., SQLite, MySQL, PostgreSQL).  The `pandas` library is helpful for this.
* **Geographic Coordinates:** Many APIs require latitude and longitude coordinates instead of city names.  You can use a geocoding API (like the Google Geocoding API) to convert city names to coordinates.
* **Licensing:**  Be aware of the licensing terms of the air quality API you use.  Some APIs may require attribution or have usage limits.

This revised code provides a much more complete and practical starting point for building a real-time air quality monitoring and health impact prediction system. Remember to adapt the code to your specific needs and the API you choose.
👁️ Viewed: 4

Comments