Spaces:
Sleeping
Sleeping
File size: 11,731 Bytes
c1f92c2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | # JalGuard - Rural Water Intelligence Platform
[](https://huggingface.co/spaces/JalGuard/Rural_Water)
[](https://github.com/Kaustavmp/Rural_Water)
[](https://www.python.org/)
[](https://fastapi.tiangolo.com/)
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
1. **Clone the repository**
```bash
git clone https://github.com/Kaustavmp/Rural_Water.git
cd Rural_Water_env
```
2. **Install dependencies**
```bash
pip install -r requirements.txt
```
3. **Set environment variables**
```bash
# Create .env file
echo "OPENAI_API_KEY=your_key_here" > .env
```
4. **Start the application**
```powershell
# Option 1: Using startup script
python start_jalguard.py
# Option 2: Using uvicorn directly
uvicorn backend.main:app --host 0.0.0.0 --port 7860
```
5. **Access 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
```bash
# .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 environment
- `POST /step` - Execute action
- `GET /state` - Get current state
- `POST /render` - Get visual representation
#### Scenarios (`/api/tasks`)
- `GET /list` - List all scenarios
- `POST /load` - Load specific scenario
- `GET /{task_id}/info` - Get scenario metadata
#### AI Copilot (`/api/ai`)
- `POST /chat` - Conversational query
- `POST /advise` - Get AI recommendations
- `POST /analyze` - Analyze current state
#### Admin (`/api/admin`)
- `GET /stats` - System statistics
- `POST /validate` - Validation tools
- `GET /logs` - Access logs and episodes
---
## π» Usage Examples
### Running the Dashboard
```bash
python start_jalguard.py
# Navigate to http://127.0.0.1:7860/dashboard
```
### Running Inference
```bash
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
```python
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:
1. **Drought Response** - Managing severe water scarcity
2. **Monsoon Overflow** - Handling excess water during monsoons
3. **Emergency Shortage** - Crisis management protocols
4. **Festival High Demand** - Managing peak usage periods
5. **Tank Leakage Crisis** - Responding to infrastructure failures
6. **Odisha Survival** - Region-specific challenges
7. **Custom Scenarios** - User-defined situations
Load a scenario:
```python
requests.post("http://localhost:7860/api/tasks/load",
json={"task_id": "drought_response"})
```
---
## π³ Docker Deployment
### Build Docker Image
```bash
docker build -t jalguard:latest .
```
### Run Container
```bash
docker run -p 7860:7860 \
-e OPENAI_API_KEY=your_key \
jalguard:latest
```
### Deploy to Hugging Face Spaces
The project includes HF Spaces integration:
```bash
git push hf master
```
---
## π Logging & Analytics
### Episode Logs
Structured logs are saved in `backend/data/logs/episodes.jsonl`:
```json
{
"episode": 1,
"scenario": "drought_response",
"actions": [...],
"total_reward": 42.5,
"timestamp": "2026-04-12T10:30:00"
}
```
### View Logs
```python
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:
```python
from backend.services.ai_service import AIService
ai = AIService(config)
response = ai.chat(message="How to handle drought?")
```
### OpenEnv Compatibility
Implements OpenEnv environment interface:
```python
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 engine
- `ai_service.py` - LLM interactions
- `scenario_loader.py` - Configuration management
- `logger.py` - Episode tracking
### Testing Inference
```bash
# 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:
```bash
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
```bash
# Use a different port
uvicorn backend.main:app --port 8080
```
### Missing API Key
```bash
# Set API key before running
export OPENAI_API_KEY=your_key_here
python start_jalguard.py
```
### Module Import Errors
```bash
# Reinstall dependencies
pip install --upgrade -r requirements.txt
```
### Clear Cache
```bash
# 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](https://github.com/Kaustavmp)
- Repository: [Rural_Water](https://github.com/Kaustavmp/Rural_Water)
---
## π€ Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to your fork
5. Submit a pull request
---
## π Resources
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
- [OpenEnv Documentation](https://docs.openenv.org/)
- [OpenAI API Reference](https://platform.openai.com/docs/)
- [Hugging Face Spaces](https://huggingface.co/spaces)
---
## π 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.
|