AI Climate Advisory System for Tanzanian Farmers

Complete Project Documentation


Version: 1.0.0
Date: January 2024
Status: MVP (Minimum Viable Product)
License: MIT License


Table of Contents

  1. Executive Summary
  2. Project Overview
  3. Problem Statement
  4. Solution Description
  5. System Architecture
  6. Technical Specifications
  7. User Guide
  8. Implementation Guide
  9. Impact & Evaluation
  10. Appendices

Executive Summary

What Is This Project?

The AI Climate Advisory System is an innovative technology solution designed to empower Tanzanian smallholder farmers with free, accessible, and actionable climate information. The system delivers personalized, crop-specific farming advice directly to farmers' mobile phones via SMS in Swahili, helping them make better decisions about planting, irrigation, and crop protection.

Key Highlights

Core Value Proposition

For Farmers:
- Receive timely weather forecasts and farming advice
- Reduce crop losses from weather-related risks
- Improve crop yields through better decision-making
- Access information in Swahili on basic mobile phones

For Government & Donors:
- Scalable solution using free data sources
- Low operational costs
- Transparent, open-source implementation
- Measurable impact on food security


Project Overview

Mission Statement

To empower Tanzanian farmers with free, accessible, and actionable climate information that helps them make better farming decisions and improve food security.

Vision

A future where every farmer in Tanzania has access to personalized, crop-specific climate advice delivered directly to their mobile phone in their own language.

Project Goals

Short-Term Goals (6 months)

Medium-Term Goals (1-2 years)

Long-Term Goals (3-5 years)

Target Audience

Primary Users

Secondary Stakeholders


Problem Statement

Challenges Facing Tanzanian Farmers

1. Unpredictable Weather Patterns

2. Limited Access to Climate Information

3. Crop Losses and Food Insecurity

4. Technology Barriers

Impact of These Problems


Solution Description

How the System Works

Simple Explanation

1. System collects weather data from satellites daily
   
2. AI analyzes data and predicts weather for next 14 days
   
3. System checks farmer's crop type and growth stage
   
4. System generates personalized advice based on:
   - Weather forecast
   - Crop needs
   - Risk assessment
   
5. Advice sent to farmer's phone via SMS in Swahili

Example Advisory Message

Swahili:

Habari! Hali ya mvua kwa Mahindi:

Mwagilia mazao yako mara mbili kwa wiki. Angalia udongo 
ukiwa na unyevu wa kutosha.

Kuna hatari ya ukame. Uhakika: Juu.

English Translation:

Hello! Rainfall conditions for Maize:

Water your crops twice per week. Ensure soil has adequate 
moisture.

Dry spell risk detected. Confidence: High.

Key Features

1. Smart Weather Forecasting

2. Crop-Specific Advice

3. Risk Alerts

4. Easy Access

5. Free & Open

Supported Crops

1. Maize (Mahindi)

2. Rice (Mpunga)

3. Beans (Maharage)

4. Sunflower (Alizeti)


System Architecture

High-Level Architecture

┌─────────────────────────────────────────────────────────────┐
│                    DATA SOURCES                              │
│  CHIRPS  ERA5  MODIS  FAO                                 │
└─────────┴──────┴───────┴────────────────────────────────────┘
                                                ▼
┌─────────────────────────────────────────────────────────────┐
│              DATA INGESTION LAYER                           │
│   Scheduled pipelines (daily/weekly)                       │
│   District-level extraction                                │
│   Local caching                                            │
└──────────────────────┬───────────────────────────────────────┘
                                              ▼
┌─────────────────────────────────────────────────────────────┐
│          FEATURE ENGINEERING LAYER                          │
│   Rainfall totals (7d, 14d, 30d)                           │
│   Rainfall anomalies                                        │
│   NDVI trends                                              │
│   Soil moisture proxy                                       │
│   Risk indicators                                          │
└──────────────────────┬───────────────────────────────────────┘
                                              ▼
┌─────────────────────────────────────────────────────────────┐
│                AI/ML LAYER                                   │
│   Rainfall forecasting (Prophet/Linear Regression)          │
│   Risk classification (Random Forest)                       │
│   Dry spell detection                                       │
│   Flood risk assessment                                    │
└──────────────────────┬───────────────────────────────────────┘
                                              ▼
┌─────────────────────────────────────────────────────────────┐
│              DECISION ENGINE                                │
│   Crop-specific rules                                      │
│   Growth stage awareness                                    │
│   Risk-based action generation                             │
│   Swahili message generation                               │
└──────────────────────┬───────────────────────────────────────┘
                                              ▼
┌─────────────────────────────────────────────────────────────┐
│           ADVISORY DELIVERY LAYER                           │
│   SMS (Twilio/Africa's Talking)                            │
│  • WhatsApp (optional)                                      │
│  • REST API                                                  │
└──────────────────────┬───────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│                    FARMERS                                   │
│  Mobile Phones (SMS/WhatsApp)                              │
└─────────────────────────────────────────────────────────────┘

System Components

1. Data Ingestion Layer

Purpose: Fetch and cache climate and satellite data from free sources

Components:
- CHIRPSIngester: Daily rainfall data for Africa
- ERA5Ingester: Temperature and weather variables from Copernicus
- MODISIngester: NDVI and land surface temperature
- FAOIngester: Crop calendars and historical yield data

Features:
- Local caching for reliability
- District-level data extraction
- Scheduled daily/weekly updates
- Graceful error handling

2. Feature Engineering Layer

Purpose: Transform raw climate data into meaningful features

Features Calculated:
- Rainfall Totals: 7-day, 14-day, 30-day rolling sums
- Rainfall Anomaly: Percentage deviation from historical mean
- NDVI Trend: Rate of change in vegetation index
- Soil Moisture Proxy: Rainfall minus evapotranspiration
- Dry Spell Indicators: Consecutive dry days, risk probability
- Flood Risk Indicators: Excess rainfall, consecutive wet days

3. AI/ML Layer

Purpose: Generate forecasts and classify risks

Models:
- RainfallForecaster: Time-series forecasting using Prophet or simple linear regression
- Forecasts 14 days ahead
- Handles seasonal patterns
- Provides confidence intervals

4. Decision Engine

Purpose: Convert predictions into actionable farming advice

Logic:
- Crop-specific rules based on growth stages
- Risk assessment (dry spell, flood, vegetation stress)
- Action generation (planting, irrigation, drainage, etc.)
- Swahili and English message generation

5. Advisory Delivery Layer

Purpose: Deliver advisories via multiple channels

Channels:
- SMS: Primary delivery method (Twilio or Africa's Talking)
- WhatsApp: Optional delivery method
- REST API: JSON output for web/mobile apps

Features:
- Swahili-first communication
- Message length optimization (160 chars for SMS)
- Delivery status tracking


Technical Specifications

Technology Stack

Backend Framework

Data Processing

Machine Learning

Database

Scheduling

SMS/WhatsApp

Deployment

Data Sources

CHIRPS (Climate Hazards Group InfraRed Precipitation with Station data)

ERA5 (Copernicus Climate Change Service)

MODIS (NASA Earth Observing System)

FAO (Food and Agriculture Organization)

API Endpoints

Advisory Endpoints

Data Endpoints

Management Endpoints


User Guide

For Farmers

How to Register

  1. Contact Agricultural Extension Officer
  2. Provide your phone number
  3. Tell them your crop type (maize, rice, beans, or sunflower)
  4. Tell them your district

  5. Receive Confirmation

  6. You'll receive an SMS confirming registration
  7. Advisories will start automatically

How to Use Advisories

  1. Receive SMS
  2. Check your phone daily for advisory messages
  3. Messages come in Swahili

  4. Read the Advice

  5. Message tells you what to do
  6. Explains why (risk explanation)
  7. Shows confidence level

  8. Take Action

  9. Follow the advice (plant, water, prepare)
  10. Monitor your crops
  11. Contact extension officer if needed

Example Scenarios

Scenario 1: Good Planting Time

Message: "Hali ya mvua ni nzuri. Unaweza kuanza kupanda mazao yako."
Action: Start planting your crops

Scenario 2: Dry Spell Warning

Message: "Kuna hatari ya ukame. Mwagilia mazao yako mara mbili kwa wiki."
Action: Water your crops twice per week

Scenario 3: Flood Warning

Message: "Mvua nyingi inatarajiwa. Fanya mifereji ya maji."
Action: Create drainage channels

For Agricultural Extension Officers

Registering Farmers

  1. Collect Information
  2. Farmer's phone number
  3. Crop type
  4. District
  5. Planting date (if known)

  6. Use API or Web Interface

  7. Call API endpoint: POST /api/v1/farmers
  8. Or use web interface (if available)

  9. Confirm Registration

  10. System sends confirmation SMS to farmer
  11. Farmer starts receiving advisories

Monitoring


Implementation Guide

Installation

Prerequisites

Step 1: Setup Environment

# Navigate to project directory
cd CWMS

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Linux/Mac:
source venv/bin/activate
# On Windows:
venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Step 2: Configuration

# Copy example configuration
cp config/config.example.yaml config/config.yaml

# Edit config/config.yaml with your settings
# - Database URL
# - SMS provider credentials
# - Data source credentials (if using real APIs)

Step 3: Initialize Database

# Create database tables
python scripts/setup_db.py

Step 4: Ingest Initial Data

# Ingest climate data for all districts
python scripts/ingest_chirps.py
python scripts/ingest_era5.py
python scripts/ingest_modis.py

Step 5: Run Application

# Development mode
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Production mode
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

Step 6: Access API

Docker Deployment

Using Docker Compose

# Build and start all services
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Manual Docker Build

# Build image
docker build -t climate-advisory .

# Run container
docker run -p 8000:8000 climate-advisory

Scheduled Tasks

Running Scheduler

# Start scheduler service
python scripts/scheduler.py

Manual Cron Jobs

Add to crontab:

# Daily CHIRPS ingestion at 6 AM
0 6 * * * cd /path/to/CWMS && python scripts/ingest_chirps.py

# Daily ERA5 ingestion at 7 AM
0 7 * * * cd /path/to/CWMS && python scripts/ingest_era5.py

# Weekly MODIS ingestion on Sunday at 8 AM
0 8 * * 0 cd /path/to/CWMS && python scripts/ingest_modis.py

# Daily advisory generation at 10 AM
0 10 * * * cd /path/to/CWMS && python scripts/generate_advisories.py

SMS Provider Setup

Twilio Setup

  1. Sign up at https://www.twilio.com
  2. Get Account SID and Auth Token
  3. Configure in config/config.yaml:
sms:
  provider: "twilio"
  twilio:
    account_sid: "your_account_sid"
    auth_token: "your_auth_token"
    from_number: "+1234567890"

Africa's Talking Setup

  1. Sign up at https://africastalking.com
  2. Get API key and username
  3. Configure in config/config.yaml:
sms:
  provider: "africas_talking"
  africas_talking:
    api_key: "your_api_key"
    username: "your_username"
    from_number: "CLIMATE"

Impact & Evaluation

Expected Impact

For Farmers

For Tanzania

For Climate Science

Success Metrics

Quantitative Metrics

Qualitative Metrics

Evaluation Framework

Phase 1: MVP Validation (Months 1-6)

Phase 2: Pilot Testing (Months 7-12)

Phase 3: Scale-Up (Months 13-24)


Appendices

Appendix A: Glossary

CHIRPS: Climate Hazards Group InfraRed Precipitation with Station data - Daily rainfall dataset for Africa

ERA5: Fifth generation ECMWF reanalysis - Global climate dataset from Copernicus

MODIS: Moderate Resolution Imaging Spectroradiometer - NASA satellite sensor for vegetation monitoring

NDVI: Normalized Difference Vegetation Index - Measure of vegetation health (0-1 scale)

Dry Spell: Period of consecutive days with little or no rainfall

Masika: Long rainy season in Tanzania (March-May)

Vuli: Short rainy season in Tanzania (October-December)

MVP: Minimum Viable Product - Initial working version of the system

Appendix B: Data Source Credentials

CHIRPS

ERA5

MODIS

Sentinel-2

Appendix C: API Reference

See docs/API.md for complete API documentation.

Appendix D: Architecture Details

See docs/ARCHITECTURE.md for detailed system architecture.

Appendix E: Deployment Guide

See docs/DEPLOYMENT.md for production deployment instructions.


Contact Information

Project Documentation

Technical Documentation

Support


Document Version: 1.0.0
Last Updated: January 2024
Status: MVP Ready for Evaluation


This project is designed to be evaluated by government institutions and international donors, with the goal of scaling to support all Tanzanian farmers.