Spaces:
Sleeping
JalGuard - Rural Water Intelligence Platform
JalGuard is an OpenEnv-compatible intelligent water management platform designed for rural community water systems. It leverages AI-powered decision making, environmental simulation, and real-time analytics to optimize water resource allocation and crisis response.
π Features
Core Capabilities
- Live Dashboard Control Center - Real-time monitoring and manual control of water systems
- Scenario Builder - Create and simulate custom water management scenarios
- Analytics & Reports - Comprehensive data visualization and performance metrics
- Admin Panel - Developer tools, validation utilities, and system diagnostics
- AI Copilot - Conversational interface with GPT-powered water management advice
- OpenEnv Integration - Compatible with OpenEnv gym-like environment simulation
Technical Highlights
- Modular FastAPI Backend - RESTful APIs for all platform operations
- Conversational AI - Integration with OpenAI GPT models
- Structured Logging - Episode-based logging for training and analysis
- Multi-Scenario Support - Predefined and custom scenario management
- Docker Ready - Containerized deployment for HuggingFace Spaces & Docker
π Project Structure
Rural_Water_env/
βββ backend/ # FastAPI application core
β βββ api/ # API route handlers
β β βββ routes_admin.py # Admin endpoints
β β βββ routes_ai.py # AI/Copilot endpoints
β β βββ routes_env.py # Environment control endpoints
β β βββ routes_tasks.py # Task management endpoints
β βββ core/ # Core logic
β β βββ environment.py # Water environment simulation
β β βββ actions.py # Action definitions
β β βββ state.py # State management
β β βββ config.py # Configuration
β βββ services/ # Business logic services
β β βββ ai_service.py # OpenAI integration
β β βββ scenario_chat.py # Scenario-based conversations
β β βββ scenario_loader.py # Scenario loading & parsing
β β βββ logger.py # Episode logging
β βββ tasks/ # Predefined scenarios
β β βββ drought_response.py
β β βββ monsoon_overflow.py
β β βββ festival_high_demand.py
β β βββ emergency_shortage_mgmt.py
β β βββ tank_leakage_crisis.py
β β βββ odisha_survival.py
β β βββ custom_user_scenario.py
β β βββ registry.py # Scenario registry
β βββ utils/ # Utilities
β β βββ validators.py # Input validation
β β βββ exceptions.py # Custom exceptions
β βββ data/ # Data storage
β β βββ logs/ # Episode logs
β β βββ scenarios/ # Scenario configurations
β βββ static/ # Frontend assets
β β βββ dashboard.html
β β βββ scenario.html
β β βββ analytics.html
β β βββ admin.html
β β βββ settings.html
β β βββ css/
β β βββ js/
β βββ main.py # FastAPI app entry point
βββ inference.py # Standalone inference script
βββ models.py # Model definitions
βββ app.py # Alternative app entry
βββ main.py # Root level main
βββ start_jalguard.py # Startup script
βββ Dockerfile # Docker configuration
βββ pyproject.toml # Python package config
βββ requirements.txt # Python dependencies
βββ README.md # Quick start guide
π Quick Start
Prerequisites
- Python 3.10+
- pip or conda
- OpenAI API Key (for AI features)
Installation
Clone the repository
git clone https://github.com/Kaustavmp/Rural_Water.git cd Rural_Water_envInstall dependencies
pip install -r requirements.txtSet environment variables
# Create .env file echo "OPENAI_API_KEY=your_key_here" > .envStart the application
# Option 1: Using startup script python start_jalguard.py # Option 2: Using uvicorn directly uvicorn backend.main:app --host 0.0.0.0 --port 7860Access the platform
- Dashboard: http://127.0.0.1:7860/dashboard
- API Docs: http://127.0.0.1:7860/docs
π§ Configuration
Environment Variables
| Variable | Default | Description |
|---|---|---|
OPENAI_API_KEY |
Required | OpenAI API key for AI features |
API_BASE_URL |
https://api.openai.com/v1 |
OpenAI API endpoint |
MODEL_NAME |
gpt-4o-mini |
Model for AI copilot |
LOG_DIR |
backend/data/logs |
Logging directory |
SCENARIOS_DIR |
backend/data/scenarios |
Scenarios directory |
Load from .env file
# .env
OPENAI_API_KEY=sk-...
MODEL_NAME=gpt-4o-mini
π‘ API Overview
Base URL
http://localhost:7860/api
Main Endpoints
Environment Control (/api/env)
POST /reset- Initialize environmentPOST /step- Execute actionGET /state- Get current statePOST /render- Get visual representation
Scenarios (/api/tasks)
GET /list- List all scenariosPOST /load- Load specific scenarioGET /{task_id}/info- Get scenario metadata
AI Copilot (/api/ai)
POST /chat- Conversational queryPOST /advise- Get AI recommendationsPOST /analyze- Analyze current state
Admin (/api/admin)
GET /stats- System statisticsPOST /validate- Validation toolsGET /logs- Access logs and episodes
π» Usage Examples
Running the Dashboard
python start_jalguard.py
# Navigate to http://127.0.0.1:7860/dashboard
Running Inference
python inference.py
The inference script generates structured logs:
[START] {"scenario": "drought_response", "episode": 1}
[STEP] {"action": "reduce_supply", "reward": 0.85}
[END] {"total_reward": 42.5, "success": true}
Using the API
import requests
# Initialize environment
response = requests.post("http://localhost:7860/api/env/reset",
json={"scenario": "drought_response"})
state = response.json()
# Execute action
action = {"type": "reduce_supply", "amount": 30}
response = requests.post("http://localhost:7860/api/env/step", json=action)
new_state = response.json()
π― Scenarios
JalGuard includes pre-built water management scenarios:
- Drought Response - Managing severe water scarcity
- Monsoon Overflow - Handling excess water during monsoons
- Emergency Shortage - Crisis management protocols
- Festival High Demand - Managing peak usage periods
- Tank Leakage Crisis - Responding to infrastructure failures
- Odisha Survival - Region-specific challenges
- Custom Scenarios - User-defined situations
Load a scenario:
requests.post("http://localhost:7860/api/tasks/load",
json={"task_id": "drought_response"})
π³ Docker Deployment
Build Docker Image
docker build -t jalguard:latest .
Run Container
docker run -p 7860:7860 \
-e OPENAI_API_KEY=your_key \
jalguard:latest
Deploy to Hugging Face Spaces
The project includes HF Spaces integration:
git push hf master
π Logging & Analytics
Episode Logs
Structured logs are saved in backend/data/logs/episodes.jsonl:
{
"episode": 1,
"scenario": "drought_response",
"actions": [...],
"total_reward": 42.5,
"timestamp": "2026-04-12T10:30:00"
}
View Logs
from backend.services.logger import EpisodeLogger
logger = EpisodeLogger("path/to/episodes.jsonl")
episodes = logger.load_episodes()
π Integration Points
OpenAI Integration
Uses OpenAI GPT models for AI copilot:
from backend.services.ai_service import AIService
ai = AIService(config)
response = ai.chat(message="How to handle drought?")
OpenEnv Compatibility
Implements OpenEnv environment interface:
from backend.core.environment import WaterEnvironment
env = WaterEnvironment()
state, reward, done, info = env.step(action)
π Development
Code Structure
- Core Logic -
backend/core/ - API Routes -
backend/api/ - Business Services -
backend/services/ - Data & Config -
backend/data/&backend/core/config.py - Utilities -
backend/utils/
Key Modules
environment.py- Main simulation engineai_service.py- LLM interactionsscenario_loader.py- Configuration managementlogger.py- Episode tracking
Testing Inference
# Standalone inference
python inference.py
# Check output logs
cat backend/data/logs/episodes.jsonl | tail -5
π Requirements
See requirements.txt for full dependencies:
- fastapi β₯0.104.0
- uvicorn β₯0.24.0
- pydantic β₯2.0.0
- numpy β₯1.26.0
- openai β₯2.7.2
- openenv-core β₯0.2.3
- python-dotenv β₯1.0.0
- requests β₯2.32.0
- PyYAML β₯6.0
π’ Deployment
GitHub
Push to main repository:
git push origin master
Hugging Face Spaces
Automatic deployment via git push hf master (HF remote configured).
CI/CD
The project is set up for automated deployments with Dockerfile.
π Troubleshooting
Port Already in Use
# Use a different port
uvicorn backend.main:app --port 8080
Missing API Key
# Set API key before running
export OPENAI_API_KEY=your_key_here
python start_jalguard.py
Module Import Errors
# Reinstall dependencies
pip install --upgrade -r requirements.txt
Clear Cache
# Remove cached files
rm -rf backend/__pycache__ backend/*/__pycache__
pip cache purge
π License
This project is licensed under the Other License. See LICENSE file for details.
π€ Author
Kaustav Priyam Mohanty
- GitHub: @Kaustavmp
- Repository: Rural_Water
π€ Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to your fork
- Submit a pull request
π Resources
π Project Status
- Version: 1.0.0
- Status: Active Development
- Last Updated: April 12, 2026
- Python: 3.10+
For issues, feature requests, or questions, please open an issue on GitHub.