Skip to content

zico-hubb/hungerless

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hungerless | Proactive Aid & Logistics Engine

A cutting-edge Anticipatory Action & Logistics Optimization Platform for food security in Kenya. Hungerless uses climate forecasts, historical yield data, and advanced AI to predict food deficits, optimize supply chains, and save lives through proactive humanitarian intervention.


Table of Contents


Overview

Hungerless addresses the critical challenge of food insecurity in East Africa by shifting from reactive humanitarian response to anticipatory action. The platform:

  1. Predicts food production deficits by analyzing climate patterns and historical yield data
  2. Optimizes logistics routes and vehicle allocation to minimize costs
  3. Estimates exact intervention budgets using real-world market and fuel prices
  4. Provides AI-powered strategic recommendations via DeepSeek reasoning models

Problem Statement

In Kenya and across the Horn of Africa, droughts cause rapid food insecurity crises. Traditional humanitarian response is slow and reactive. Hungerless enables NGOs, government agencies, and donors to:

  • Identify food deficit regions 3-6 months in advance
  • Plan supply chains with precision
  • Allocate budgets efficiently
  • Reduce delivery time and food waste

Key Features

1. Predictive Risk Assessment

  • Analyzes historical climate and yield data (2015-2025)
  • Compares rainfall forecasts against historical baselines
  • Predicts county-level crop yields using non-linear climate-yield models
  • Categorizes regions as Critical Deficit, Surplus, or Stable

2. Interactive Risk Map

  • Real-time visualization of food security status across Kenyan counties
  • Color-coded markers: 🔴 Deficit, 🟢 Surplus, 🔵 Stable
  • Built with Folium for geographic intelligence

3. Dynamic Logistics Planner

  • AI-recommended routes matching surplus to deficit counties
  • Manual route customization for operational flexibility
  • Real-time distance calculation using Haversine formula
  • Multi-fleet vehicle options (5-ton light trucks to 28-ton heavy trailers)

4. Precise Cost Calculation

  • Fuel costs: Based on March 2026 EPRA diesel rates (KSh 166.54/L)
  • Food procurement: Real maize market prices (KSh 44,444/ton)
  • Fleet optimization: Calculates minimum trucks needed for each route
  • Exports detailed logistics plans as CSV

5. AI-Powered Strategy Consultant

  • Integrates Featherless AI's DeepSeek-V3.2 model
  • Analyzes drought patterns, security risks, and alternative interventions
  • Generates executive summaries for stakeholder briefings
  • Provides ROI analysis and pastoral aid recommendations

6. Data Management

  • Upload historical climate, livestock, and forecast CSVs
  • Real-time data validation and preprocessing
  • Sample data generator for testing (2015-2025 historical records)

🛠 Technology Stack

Layer Technology
Frontend Streamlit (Python web framework)
Visualization Folium (maps), Plotly (charts)
Data Processing Pandas, NumPy
AI/ML Featherless API (DeepSeek-V3.2)
APIs OpenAI client (routed to Featherless)
Geospatial Haversine formula, GPS coordinates
Backend Python 3.8+
Environment Python venv or conda

Architecture

User Interface (Streamlit)
         ↓
┌─────────────────────────────┐
│   Data Upload & Validation  │
│  (Climate, Livestock, Prep) │
└────────────┬────────────────┘
             ↓
┌─────────────────────────────┐
│  Prediction Engine          │
│  (Yield Forecasting)        │
└────────────┬────────────────┘
             ↓
┌─────────────────────────┐   ┌────────────────────────┐
│  Matching Engine        │   │  Logistics Engine      │
│  (Route Optimization)   │←→─│  (Cost Calculation)    │
└────────────┬────────────┘   └────────────────────────┘
             ↓
┌──────────────────────────────┐
│ Featherless AI Integration   │
│ (DeepSeek Strategy Advisor)  │
└──────────────────────────────┘
             ↓
       Dashboard Output

Data Flow

  1. Upload → User uploads 3 CSV files (historical climate, livestock impact, seasonal forecast)
  2. Processprediction.py compares forecasts to historical baselines
  3. Optimizematching.py identifies surplus/deficit matches using GPS coordinates
  4. Calculatelogistics.py estimates costs for each route with selected vehicles
  5. Adviseapp.py queries Featherless AI for strategic recommendations
  6. Visualize → Streamlit dashboard displays maps, metrics, and charts

Installation & Setup

Prerequisites

  • Python 3.8 or higher
  • pip or conda package manager
  • API key for Featherless AI (free tier available)
  • Internet connection for API calls

Step 1: Clone the Repository

cd c:\Users\zico\Desktop\relief_exchange

Step 2: Create Virtual Environment

# Using venv
python -m venv venv
venv\Scripts\activate  # On Windows
# OR
source venv/bin/activate  # On macOS/Linux

# OR using conda
conda create -n hungerless python=3.8
conda activate hungerless

Step 3: Install Dependencies

pip install -r requirements.txt

Step 4: Set Up Environment Variables

Create a .env file in the project root:

FEATHERLESS_API_KEY=your_featherless_api_key_here

Get your free Featherless API key from: https://featherless.ai

Step 5: Prepare Data (Optional)

To generate sample data for testing:

python utils/data_generator.py

This creates CSV files in data/raw/:

  • historical_climate_yield.csv (2015-2025 records)
  • historical_livestock_impact.csv (market prices & mortality rates)
  • current_forecast.csv (upcoming season predictions)

Quick Start

Launch the Application

streamlit run app.py

The dashboard will open at http://localhost:8501

Step-by-Step Usage

  1. Upload Data

    • In the left sidebar under "📁 Data Upload Center"
    • Upload 3 CSV files in order:
      • Historical Climate data
      • Historical Livestock data
      • Season Forecast data
  2. View Risk Assessment

    • Tab 1 " Risk Map" shows colored county markers
    • Red = Critical Deficit, Green = Surplus, Gray = Stable
    • Click "Generate AI Risk Briefing" for analysis
  3. Plan Logistics

    • Tab 2 " Dynamic Logistics Planner"
    • Choose between AI-recommended or custom routes
    • Select vehicle type (5-ton, 10-ton, or 28-ton trucks)
    • View financial breakdown
    • Download optimization plan as CSV
  4. Consult AI Strategist

    • Tab 4 " Featherless AI Strategist"
    • Ask operational questions
    • Preset buttons for ROI, security, and pastoral aid analysis
    • Get DeepSeek reasoning in real-time

Project Structure

relief_exchange/
├── app.py                          # Main Streamlit application
├── requirements.txt                # Python dependencies
├── README.md                       # This file
├── .env                            # Environment variables (IGNORED in git)
│
├── engines/                        # Core computation modules
│   ├── __init__.py
│   ├── prediction.py              # Yield forecasting algorithm
│   ├── matching.py                # Route optimization & GPS distance
│   └── logistics.py               # Cost calculation & fleet management
│
├── components/                    # UI components (placeholder structure)
│   ├── __init__.py
│   ├── maps.py                    # Map visualization library (empty)
│   └── stats.py                   # Statistics display (empty)
│
├── utils/                         # Utility functions
│   ├── data_generator.py          # Synthetic data creation for testing
│   └── helpers.py                 # General helper functions (empty)
│
└── data/                          # Data directory
    ├── raw/                       # Raw input CSV files
    │   ├── historical_climate_yield.csv
    │   ├── historical_livestock_impact.csv
    │   └── current_forecast.csv
    └── processed/                 # Processed data outputs (generated)

Core Modules

1. engines/prediction.py - Risk Assessment Engine

Predicts food security outcomes by analyzing climate-yield relationships.

Main Function: run_risk_assessment(df_climate, df_forecast)

Algorithm:

  1. Calculate historical rainfall & yield averages per county
  2. Compute rainfall deviation: (Forecast_Rain - Avg_Rain) / Avg_Rain
  3. Apply yield prediction: Predicted_Yield = Base_Yield × (1 + 1.2 × Rainfall_Deviation)
  4. Categorize counties:
    • Critical Deficit: Yield < 75% of historical average
    • Surplus: Yield > 105% of historical average
    • Stable: Between 75% and 105%

Output: DataFrame with columns: County, Alert Status, Predicted Yield, Historical Avg Yield


2. engines/matching.py - Route Optimization Engine

Matches surplus counties to deficit counties and calculates distances.

Key Components:

  • COUNTY_COORDS: GPS coordinates for 6 focus counties
  • get_distance(county1, county2): Haversine formula for great-circle distance
  • generate_action_plan(risk_report): Creates optimized food transfer routes

Supported Counties:

  • Uasin Gishu (0.5143°, 35.2698°)
  • Trans Nzoia (1.0191°, 34.9367°)
  • Machakos (-1.5177°, 37.2634°)
  • Kitui (-1.3667°, 38.0167°)
  • Marsabit (2.3333°, 37.9833°)
  • Turkana (3.1167°, 35.6000°)

Output: DataFrame with routes, distances, and tons needed


3. engines/logistics.py - Cost Optimization Engine

Calculates exact financial costs for food interventions.

Fleet Options:

Vehicle Capacity Fuel Efficiency
Isuzu NPR (Light) 5 tons 6.0 km/L
Isuzu FVR (Medium) 10 tons 4.5 km/L
Scania 6-Axle (Heavy) 28 tons 2.2 km/L

Cost Components:

  1. Fuel Cost = (Round-trip Distance × Number of Trucks) / Fuel Efficiency × Diesel Price
  2. Food Cost = Tons Needed × Market Price per Ton
  3. Total Cost = Fuel Cost + Food Cost

Data Sources:

  • Diesel Price: KSh 166.54/L (EPRA March 2026)
  • Maize Price: KSh 44,444/ton (~KSh 4,000 per 90kg bag)

4. app.py - Streamlit Frontend

Main user interface with 4 tabs:

Tab 1: Risk Map

  • Interactive Folium map with county status markers
  • Alert status table
  • AI Risk Briefing button

Tab 2: Dynamic Logistics Planner

  • Route selector (AI-recommended or custom)
  • Vehicle selection
  • Financial breakdown metrics
  • CSV export functionality
  • Executive summary generator

Tab 3: Raw Data

  • Display uploaded climate/forecast data

Tab 4: AI Strategist

  • Free-form question input to DeepSeek
  • Preset quick-prompts (ROI, security risks, pastoral aid)
  • Contextual analysis with live data

Data Formats

1. Historical Climate & Yield CSV

Required Columns:

Year, County, Rainfall_mm, Temperature_C, Maize_Yield_Tons_Per_Hectare
2025, Machakos, 598.5, 26.3, 1.95
2025, Turkana, 180.2, 31.1, 0.08

2. Historical Livestock Impact CSV

Required Columns:

Year, County, Livestock_Mortality_Percent, Market_Price_KES_Per_90kg_Bag
2025, Marsabit, 12.5, 3850
2025, Kitui, 6.2, 4100

3. Seasonal Forecast CSV

Required Columns:

County, Predicted_Rainfall_mm, Predicted_Min_Temp_C, Predicted_Max_Temp_C
Uasin Gishu, 1120.0, 18.5, 28.0
Trans Nzoia, 1050.5, 17.0, 27.5

Configuration

Environment Variables (.env)

# Featherless AI Configuration
FEATHERLESS_API_KEY=your_api_key_here

# Optional: Custom API endpoint (defaults to featherless.ai)
# FEATHERLESS_BASE_URL=https://api.featherless.ai/v1

# Optional: Model selection
# DEEPSEEK_MODEL=deepseek-ai/DeepSeek-V3.2

Sensitivity Tuning (in engines/prediction.py)

Modify the yield prediction sensitivity:

# Beta factor (default: 1.2)
# Higher = more sensitive to rainfall changes
analysis['Predicted_Yield'] = analysis['Maize_Yield_Tons_Per_Hectare'] * (1 + BETA * rainfall_deviation)

Threshold Tuning (in engines/prediction.py)

Adjust deficit/surplus thresholds:

# Deficit threshold (default: 75% of average)
if row['Predicted_Yield'] < (row['Maize_Yield_Tons_Per_Hectare'] * 0.75):
    return " CRITICAL DEFICIT"

# Surplus threshold (default: 105% of average)
elif row['Predicted_Yield'] > (row['Maize_Yield_Tons_Per_Hectare'] * 1.05):
    return "✅ SURPLUS"

Usage Guide

For NGO Coordinators

  1. Upload latest climate forecast and historical data
  2. Use "Dynamic Logistics Planner" to estimate budget needs
  3. Download action plan CSV for partnership coordination
  4. Use AI Strategist to validate assumptions with DeepSeek

For Government Officials

  1. Review Risk Map for national food security assessment
  2. Use multi-route planning to coordinate regional responses
  3. Export data for official reports and cabinet briefings
  4. Consult AI for inter-county coordination strategies

For Donors & Stakeholders

  1. View financial breakdown to understand cost structure
  2. Get AI-generated executive summaries for board meetings
  3. Assess ROI of interventions through dedicated AI prompts
  4. Track intervention history through exported CSVs

AI Integration

Featherless AI (DeepSeek-V3.2)

Hungerless integrates DeepSeek-V3.2, an advanced reasoning model, via Featherless AI's infrastructure.

What DeepSeek Powers:

  1. Risk Briefing: Summarizes drought patterns and recommends priorities
  2. Executive Summaries: Drafts 3-sentence justifications for interventions
  3. Strategic Analysis: Answers free-form questions about:
    • ROI of specific interventions
    • Security risks in conflict zones
    • Alternative pastoral/livestock aid
    • Supply chain vulnerabilities
    • Cross-border coordination needs

Integration Details:

client = OpenAI(
    api_key=os.getenv("FEATHERLESS_API_KEY"),
    base_url="https://api.featherless.ai/v1"
)

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V3.2",
    messages=[
        {"role": "system", "content": "You are an expert NGO logistics advisor in Kenya..."},
        {"role": "user", "content": prompt}
    ]
)

System Prompt:

"You are an expert NGO logistics advisor in Kenya. Keep responses professional, data-driven, and highly concise."


Key Algorithms

1. Yield Prediction Algorithm

Purpose: Forecast maize production based on rainfall deviation

Input:  Historical rainfall, historical yield, forecasted rainfall
Output: Predicted yield for upcoming season

Formula:
  Rainfall_Deviation = (Forecast_Rain - Historical_Rain) / Historical_Rain
  Predicted_Yield = Base_Yield × (1 + β × Rainfall_Deviation)
  
  where β = 1.2 (rain sensitivity factor for maize)
  
Example:
  Historical: 600mm rain → 2.0 tons/ha yield
  Forecast: 450mm rain (25% below average)
  Deviation: -0.25
  Predicted: 2.0 × (1 + 1.2 × -0.25) = 2.0 × 0.7 = 1.4 tons/ha
  Status: CRITICAL DEFICIT (below 75% threshold of 1.5 tons/ha)

2. Distance Calculation (Haversine Formula)

Purpose: Calculate great-circle distance between two GPS coordinates

Input:  Latitude & Longitude of two counties
Output: Distance in kilometers

Formula:
  a = sin²(Δlat/2) + cos(lat1) × cos(lat2) × sin²(Δlon/2)
  c = 2 × atan2(√a, √(1-a))
  d = R × c (where R = 6,371 km)
  
Example:
  Source: Uasin Gishu (0.5143°, 35.2698°)
  Dest:   Machakos (-1.5177°, 37.2634°)
  Distance: ~320 km

3. Fleet Optimization Algorithm

Purpose: Determine minimum vehicles needed and calculate total costs

Input:  Tons to move, distance, vehicle type
Output: Fleet size, fuel cost, total cost

Algorithm:
  1. Trucks_Needed = ⌈Tons_Needed / Truck_Capacity⌉
  2. Fuel_Liters = (Round_Trip_Distance × Trucks_Needed) / Fuel_Efficiency
  3. Fuel_Cost = Fuel_Liters × Diesel_Price
  4. Food_Cost = Tons_Needed × Market_Price_Per_Ton
  5. Total = Fuel_Cost + Food_Cost

Example:
  Move 5,000 tons from Uasin Gishu to Machakos using 28-ton trucks
  Trucks: ⌈5000/28⌉ = 179 trucks
  Distance: 320 km × 2 (round trip) × 179 = 114,560 km
  Fuel: 114,560 / 2.2 = 52,073 liters
  Fuel Cost: 52,073 × 166.54 = KSh 8,673,261
  Food Cost: 5,000 × 44,444 = KSh 222,220,000
  Total: KSh 230,893,261

CSV Export Format

The downloadable "Action Plan" CSV includes:

Source (Surplus),Destination (Deficit),Tons Needed,Distance (km)
Uasin Gishu,Machakos,3500,320
Trans Nzoia,Kitui,2100,285
Uasin Gishu,Marsabit,1800,580

Used for:

  • Partnership coordination between source/destination counties
  • Integration with logistics management systems
  • Historical documentation of interventions
  • Data analysis and impact assessment

Troubleshooting

Issue: "Featherless API Key missing"

Solution:

  • Create .env file in project root
  • Add FEATHERLESS_API_KEY=your_key_here
  • Restart Streamlit app

Issue: "Connection failed" from AI Strategist

Solution:

  • Check internet connection
  • Verify API key is valid (test at https://api.featherless.ai)
  • Check rate limits (free tier: 50 requests/day)

Issue: "No data uploaded"

Solution:

  • Ensure all 3 CSV files are uploaded
  • Check CSV format matches required columns
  • Use data generator for sample data: python utils/data_generator.py

Issue: Map markers not showing

Solution:

  • Verify county names in CSV match COUNTY_COORDS dictionary
  • Supported counties: Uasin Gishu, Trans Nzoia, Machakos, Kitui, Marsabit, Turkana

Contributing

Development Setup

# Clone and install
git clone <repo-url>
cd relief_exchange
python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt

# Create feature branch
git checkout -b feature/your-feature-name

# Make changes and test
streamlit run app.py

# Commit and push
git add .
git commit -m "Add your feature"
git push origin feature/your-feature-name

Areas for Enhancement

  • Add more counties and GPS coordinates
  • Implement seasonal adjustment factors
  • Add livestock pricing predictions
  • Create intervention impact dashboard
  • Add multi-language support (Swahili, Somali)
  • Integrate with actual climate APIs (NOAA, ECMWF)
  • Build API layer for programmatic access
  • Add user authentication for NGO organizations
  • Implement real-time truck tracking
  • Create mobile app version

Support & Contact

For questions, issues, or feature requests:

  • Email: (mosesszico@gmail.com)
  • GitHub Issues: (zico-hubb)
  • Documentation: See this README and code comments

License

This project is open-source and available under the MIT License. See LICENSE file for details.


Acknowledgments

  • Featherless AI for providing DeepSeek-V3.2 reasoning model
  • Streamlit for the rapid web framework
  • Kenya meteorological institutes for climate data sources
  • EPRA & KeNHA for vehicle and fuel data
  • NGO partners for real-world logistics insights

References

  1. Yield-Rain Relationship: Non-linear crop response to precipitation (β=1.2 empirically determined for East African maize)
  2. Haversine Formula: Accurate distance calculation on Earth's surface
  3. EPRA Data: Kenya pump prices, March 2026
  4. Truck Specifications: Standard commercial vehicle profiles used in East African logistics

Last Updated: March 22, 2026
Version: 1.0.0
Status: Production Ready

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages