Spaces:
Sleeping
Sleeping
Commit ·
9d5d2ab
1
Parent(s): acbbeb5
updated some files
Browse files- Dockerfile +1 -75
- my_env/README.md +16 -11
- my_env/__pycache__/baseline.cpython-313.pyc +0 -0
- my_env/__pycache__/graders.cpython-313.pyc +0 -0
- my_env/graders.py +0 -164
- my_env/server/__init__.py +0 -11
- my_env/server/__pycache__/__init__.cpython-313.pyc +0 -0
- my_env/server/__pycache__/__init__.cpython-314.pyc +0 -0
- my_env/server/__pycache__/app.cpython-313.pyc +0 -0
- my_env/server/__pycache__/app.cpython-314.pyc +0 -0
- my_env/server/__pycache__/my_env_environment.cpython-313.pyc +0 -0
- my_env/server/__pycache__/my_env_environment.cpython-314.pyc +0 -0
- my_env/server/app.py +0 -275
- my_env/server/my_env_environment.py +0 -242
- my_env/server/requirements.txt +0 -6
- openenv.yaml +1 -2
- openenv_my_env.egg-info/SOURCES.txt +4 -4
- openenv_my_env.egg-info/entry_points.txt +1 -1
- openenv_my_env.egg-info/top_level.txt +1 -0
- pyproject.toml +3 -3
- server/__pycache__/app.cpython-313.pyc +0 -0
- server/__pycache__/my_env_environment.cpython-313.pyc +0 -0
- server/app.py +9 -12
- server/my_env_environment.py +20 -246
- server/requirements.txt +0 -2
Dockerfile
CHANGED
|
@@ -10,80 +10,6 @@
|
|
| 10 |
# - Standalone environments (with openenv from PyPI/Git)
|
| 11 |
# The build script (openenv build) handles context detection and sets appropriate build args.
|
| 12 |
|
| 13 |
-
# ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
|
| 14 |
-
# FROM ${BASE_IMAGE} AS builder
|
| 15 |
-
|
| 16 |
-
# WORKDIR /app
|
| 17 |
-
|
| 18 |
-
# # Ensure git is available (required for installing dependencies from VCS)
|
| 19 |
-
# RUN apt-get update && \
|
| 20 |
-
# apt-get install -y --no-install-recommends git && \
|
| 21 |
-
# rm -rf /var/lib/apt/lists/*
|
| 22 |
-
|
| 23 |
-
# # Build argument to control whether we're building standalone or in-repo
|
| 24 |
-
# ARG BUILD_MODE=in-repo
|
| 25 |
-
# ARG ENV_NAME=my_env
|
| 26 |
-
|
| 27 |
-
# # Copy environment code (always at root of build context)
|
| 28 |
-
# COPY . /app/env
|
| 29 |
-
|
| 30 |
-
# # For in-repo builds, openenv is already vendored in the build context
|
| 31 |
-
# # For standalone builds, openenv will be installed via pyproject.toml
|
| 32 |
-
# WORKDIR /app/env
|
| 33 |
-
|
| 34 |
-
# # Ensure uv is available (for local builds where base image lacks it)
|
| 35 |
-
# RUN if ! command -v uv >/dev/null 2>&1; then \
|
| 36 |
-
# curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 37 |
-
# mv /root/.local/bin/uv /usr/local/bin/uv && \
|
| 38 |
-
# mv /root/.local/bin/uvx /usr/local/bin/uvx; \
|
| 39 |
-
# fi
|
| 40 |
-
|
| 41 |
-
# # Install dependencies using uv sync
|
| 42 |
-
# # If uv.lock exists, use it; otherwise resolve on the fly
|
| 43 |
-
# RUN --mount=type=cache,target=/root/.cache/uv \
|
| 44 |
-
# if [ -f uv.lock ]; then \
|
| 45 |
-
# uv sync --frozen --no-install-project --no-editable; \
|
| 46 |
-
# else \
|
| 47 |
-
# uv sync --no-install-project --no-editable; \
|
| 48 |
-
# fi
|
| 49 |
-
|
| 50 |
-
# RUN --mount=type=cache,target=/root/.cache/uv \
|
| 51 |
-
# if [ -f uv.lock ]; then \
|
| 52 |
-
# uv sync --frozen --no-editable; \
|
| 53 |
-
# else \
|
| 54 |
-
# uv sync --no-editable; \
|
| 55 |
-
# fi
|
| 56 |
-
|
| 57 |
-
# # Final runtime stage
|
| 58 |
-
# FROM ${BASE_IMAGE}
|
| 59 |
-
|
| 60 |
-
# WORKDIR /app
|
| 61 |
-
|
| 62 |
-
# # Copy the virtual environment from builder
|
| 63 |
-
# COPY --from=builder /app/env/.venv /app/.venv
|
| 64 |
-
|
| 65 |
-
# # Copy the environment code
|
| 66 |
-
# COPY --from=builder /app/env /app/env
|
| 67 |
-
|
| 68 |
-
# # Set PATH to use the virtual environment
|
| 69 |
-
# ENV PATH="/app/.venv/bin:$PATH"
|
| 70 |
-
|
| 71 |
-
# # Set PYTHONPATH so imports work correctly
|
| 72 |
-
# ENV PYTHONPATH="/app:/app/my_env:$PYTHONPATH"
|
| 73 |
-
|
| 74 |
-
# # Required LLM credentials for inference.py
|
| 75 |
-
# ENV API_BASE_URL="https://router.huggingface.co/v1"
|
| 76 |
-
# ENV MODEL_NAME="meta-llama/Llama-3.3-70B-Instruct"
|
| 77 |
-
# ENV HF_TOKEN=""
|
| 78 |
-
|
| 79 |
-
# # Health check
|
| 80 |
-
# HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
| 81 |
-
# CMD curl -f http://localhost:8000/health || exit 1
|
| 82 |
-
|
| 83 |
-
# # Run the FastAPI server
|
| 84 |
-
# # The module path is constructed to work with the /app/env structure
|
| 85 |
-
# CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
|
| 86 |
-
|
| 87 |
FROM python:3.10
|
| 88 |
|
| 89 |
WORKDIR /app
|
|
@@ -92,6 +18,7 @@ COPY . .
|
|
| 92 |
COPY openenv.yaml /app/server/openenv.yaml
|
| 93 |
COPY openenv.yaml /app/openenv.yaml
|
| 94 |
|
|
|
|
| 95 |
RUN pip install --no-cache-dir -r server/requirements.txt
|
| 96 |
|
| 97 |
ENV PYTHONPATH="/app:/app/my_env:$PYTHONPATH"
|
|
@@ -101,5 +28,4 @@ RUN /app/.venv/bin/pip install openenv-core || \
|
|
| 101 |
/app/.venv/bin/python -m pip install openenv-core || \
|
| 102 |
pip install openenv-core
|
| 103 |
|
| 104 |
-
# CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "8000"]
|
| 105 |
CMD ["sh", "-c", "cd /app && uvicorn server.app:app --host 0.0.0.0 --port 7860"]
|
|
|
|
| 10 |
# - Standalone environments (with openenv from PyPI/Git)
|
| 11 |
# The build script (openenv build) handles context detection and sets appropriate build args.
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
FROM python:3.10
|
| 14 |
|
| 15 |
WORKDIR /app
|
|
|
|
| 18 |
COPY openenv.yaml /app/server/openenv.yaml
|
| 19 |
COPY openenv.yaml /app/openenv.yaml
|
| 20 |
|
| 21 |
+
RUN pip install --no-cache-dir openenv-core
|
| 22 |
RUN pip install --no-cache-dir -r server/requirements.txt
|
| 23 |
|
| 24 |
ENV PYTHONPATH="/app:/app/my_env:$PYTHONPATH"
|
|
|
|
| 28 |
/app/.venv/bin/python -m pip install openenv-core || \
|
| 29 |
pip install openenv-core
|
| 30 |
|
|
|
|
| 31 |
CMD ["sh", "-c", "cd /app && uvicorn server.app:app --host 0.0.0.0 --port 7860"]
|
my_env/README.md
CHANGED
|
@@ -220,21 +220,26 @@ Set them before running inference or deployment.
|
|
| 220 |
|
| 221 |
## 📁 Project Structure
|
| 222 |
```
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
├──
|
| 228 |
-
├──
|
| 229 |
-
├──
|
| 230 |
-
├──
|
| 231 |
-
├──
|
| 232 |
-
├──
|
|
|
|
| 233 |
│
|
| 234 |
└── server/
|
| 235 |
├── app.py # Main server + API endpoints
|
| 236 |
├── my_env_environment.py # Farm environment logic
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
```
|
| 239 |
|
| 240 |
---
|
|
|
|
| 220 |
|
| 221 |
## 📁 Project Structure
|
| 222 |
```
|
| 223 |
+
Meta-Hackathon-Project
|
| 224 |
+
|
|
| 225 |
+
--- my_env/
|
| 226 |
+
│
|
| 227 |
+
├── models.py # Data shapes (Observation, Action)
|
| 228 |
+
├── weather.py # Live weather API integration
|
| 229 |
+
├── baseline.py # Baseline agent script
|
| 230 |
+
├── tasks.py # 3 task definitions
|
| 231 |
+
├── graders.py # Scoring logic for each task
|
| 232 |
+
├── client.py # Environment client
|
| 233 |
+
├── README.md # This file!
|
| 234 |
│
|
| 235 |
└── server/
|
| 236 |
├── app.py # Main server + API endpoints
|
| 237 |
├── my_env_environment.py # Farm environment logic
|
| 238 |
+
|___ requirements.txt # Required versions to run this project
|
| 239 |
+
|
|
| 240 |
+
└── Dockerfile # Docker packaging
|
| 241 |
+
|___openenv.yaml # Environment config
|
| 242 |
+
|___inference.py # LLM agent decides crop watering.
|
| 243 |
```
|
| 244 |
|
| 245 |
---
|
my_env/__pycache__/baseline.cpython-313.pyc
CHANGED
|
Binary files a/my_env/__pycache__/baseline.cpython-313.pyc and b/my_env/__pycache__/baseline.cpython-313.pyc differ
|
|
|
my_env/__pycache__/graders.cpython-313.pyc
CHANGED
|
Binary files a/my_env/__pycache__/graders.cpython-313.pyc and b/my_env/__pycache__/graders.cpython-313.pyc differ
|
|
|
my_env/graders.py
CHANGED
|
@@ -1,167 +1,3 @@
|
|
| 1 |
-
# # graders.py — reward functions and graders for all 3 tasks
|
| 2 |
-
|
| 3 |
-
# def health_to_number(crop_health_str) -> int:
|
| 4 |
-
# """
|
| 5 |
-
# Converts crop health string to number for grading.
|
| 6 |
-
# poor=25, fair=50, good=75, excellent=100
|
| 7 |
-
# """
|
| 8 |
-
# mapping = {
|
| 9 |
-
# "poor": 25,
|
| 10 |
-
# "fair": 50,
|
| 11 |
-
# "good": 75,
|
| 12 |
-
# "excellent": 100
|
| 13 |
-
# }
|
| 14 |
-
# if isinstance(crop_health_str, (int, float)):
|
| 15 |
-
# return int(crop_health_str)
|
| 16 |
-
# return mapping.get(str(crop_health_str).lower(), 50)
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
# def compute_reward(soil_moisture, crop_health, water_action, rainfall, temperature=30):
|
| 20 |
-
# """
|
| 21 |
-
# Returns a daily score between -1.0 and 1.0
|
| 22 |
-
# Now considers temperature too!
|
| 23 |
-
# """
|
| 24 |
-
# reward = 0.0
|
| 25 |
-
|
| 26 |
-
# # Moisture check — ideal is 40% to 70%
|
| 27 |
-
# if 40 <= soil_moisture <= 70:
|
| 28 |
-
# reward += 0.5
|
| 29 |
-
# elif 30 <= soil_moisture < 40 or 70 < soil_moisture <= 80:
|
| 30 |
-
# reward += 0.2
|
| 31 |
-
# else:
|
| 32 |
-
# reward -= 0.3
|
| 33 |
-
|
| 34 |
-
# # Crop health check
|
| 35 |
-
# health_num = health_to_number(crop_health)
|
| 36 |
-
# if health_num >= 70:
|
| 37 |
-
# reward += 0.3
|
| 38 |
-
# elif health_num >= 50:
|
| 39 |
-
# reward += 0.1
|
| 40 |
-
# else:
|
| 41 |
-
# reward -= 0.2
|
| 42 |
-
|
| 43 |
-
# # Penalize watering heavily when raining a lot
|
| 44 |
-
# if rainfall > 15 and water_action == 3:
|
| 45 |
-
# reward -= 0.2
|
| 46 |
-
|
| 47 |
-
# # Penalize not watering enough on very hot days
|
| 48 |
-
# if temperature >= 38 and soil_moisture < 40 and water_action == 0:
|
| 49 |
-
# reward -= 0.2
|
| 50 |
-
|
| 51 |
-
# return round(max(-1.0, min(1.0, reward)), 2)
|
| 52 |
-
|
| 53 |
-
# # TASK 1 GRADER — Easy (7 days)
|
| 54 |
-
|
| 55 |
-
# def grade_task1(episode_history):
|
| 56 |
-
# """
|
| 57 |
-
# Score = fraction of days where moisture was between 40-70%
|
| 58 |
-
# Returns 0.0 to 1.0
|
| 59 |
-
# """
|
| 60 |
-
# if not episode_history:
|
| 61 |
-
# return 0.0
|
| 62 |
-
|
| 63 |
-
# days_in_range = 0
|
| 64 |
-
# for record in episode_history:
|
| 65 |
-
# moisture = record.get("soil_moisture", 0)
|
| 66 |
-
# if 40 <= moisture <= 70:
|
| 67 |
-
# days_in_range += 1
|
| 68 |
-
|
| 69 |
-
# score = days_in_range / len(episode_history)
|
| 70 |
-
# return round(score, 2)
|
| 71 |
-
|
| 72 |
-
# # TASK 2 GRADER — Medium (14 days)
|
| 73 |
-
|
| 74 |
-
# def grade_task2(episode_history):
|
| 75 |
-
# """
|
| 76 |
-
# Score based on daily rewards across 14 days with weather.
|
| 77 |
-
# Returns 0.0 to 1.0
|
| 78 |
-
# """
|
| 79 |
-
# if not episode_history:
|
| 80 |
-
# return 0.0
|
| 81 |
-
|
| 82 |
-
# total_reward = 0.0
|
| 83 |
-
# max_possible = len(episode_history) * 0.8
|
| 84 |
-
|
| 85 |
-
# for record in episode_history:
|
| 86 |
-
# daily = compute_reward(
|
| 87 |
-
# record.get("soil_moisture", 0),
|
| 88 |
-
# health_to_number(record.get("crop_health", "fair")),
|
| 89 |
-
# record.get("water_action", 0),
|
| 90 |
-
# record.get("rainfall", 0),
|
| 91 |
-
# record.get("temperature", 30)
|
| 92 |
-
# )
|
| 93 |
-
# total_reward += daily
|
| 94 |
-
|
| 95 |
-
# score = total_reward / max_possible if max_possible > 0 else 0.0
|
| 96 |
-
# return round(max(0.0, min(1.0, score)), 2)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# # TASK 3 GRADER — Hard (30 days)
|
| 100 |
-
|
| 101 |
-
# def grade_task3(episode_history):
|
| 102 |
-
# """
|
| 103 |
-
# Score based on crop stage requirements over 30 days.
|
| 104 |
-
# Seedling (days 1-10), Growing (days 11-20), Mature (days 21-30)
|
| 105 |
-
# Returns 0.0 to 1.0
|
| 106 |
-
# """
|
| 107 |
-
# if not episode_history:
|
| 108 |
-
# return 0.0
|
| 109 |
-
|
| 110 |
-
# day_scores = []
|
| 111 |
-
|
| 112 |
-
# for record in episode_history:
|
| 113 |
-
# day = record.get("day") or record.get("day_number", 1)
|
| 114 |
-
# moisture = record.get("soil_moisture", 0)
|
| 115 |
-
# crop_health = health_to_number(record.get("crop_health", "fair"))
|
| 116 |
-
# temperature = record.get("temperature", 30)
|
| 117 |
-
|
| 118 |
-
# # Each stage needs different moisture
|
| 119 |
-
# if day <= 10: # Seedling
|
| 120 |
-
# ideal = 50 <= moisture <= 75
|
| 121 |
-
# elif day <= 20: # Growing
|
| 122 |
-
# ideal = 45 <= moisture <= 70
|
| 123 |
-
# else: # Mature
|
| 124 |
-
# ideal = 35 <= moisture <= 60
|
| 125 |
-
|
| 126 |
-
# # Extra credit for managing hot days well
|
| 127 |
-
# hot_day_managed = temperature >= 38 and moisture >= 40
|
| 128 |
-
|
| 129 |
-
# if ideal and crop_health >= 70:
|
| 130 |
-
# day_scores.append(1.0)
|
| 131 |
-
# elif ideal or crop_health >= 60:
|
| 132 |
-
# day_scores.append(0.5)
|
| 133 |
-
# elif hot_day_managed:
|
| 134 |
-
# day_scores.append(0.3)
|
| 135 |
-
# else:
|
| 136 |
-
# day_scores.append(0.0)
|
| 137 |
-
|
| 138 |
-
# score = sum(day_scores) / len(day_scores)
|
| 139 |
-
# return round(score, 2)
|
| 140 |
-
|
| 141 |
-
# # TEST
|
| 142 |
-
|
| 143 |
-
# if __name__ == "__main__":
|
| 144 |
-
# fake_7 = [
|
| 145 |
-
# {"day": i, "soil_moisture": 55, "crop_health": "good",
|
| 146 |
-
# "water_action": 2, "rainfall": 0, "temperature": 32}
|
| 147 |
-
# for i in range(1, 8)
|
| 148 |
-
# ]
|
| 149 |
-
# fake_14 = [
|
| 150 |
-
# {"day": i, "soil_moisture": 50 + i, "crop_health": "fair",
|
| 151 |
-
# "water_action": 1, "rainfall": i % 3, "temperature": 30 + i}
|
| 152 |
-
# for i in range(1, 15)
|
| 153 |
-
# ]
|
| 154 |
-
# fake_30 = [
|
| 155 |
-
# {"day": i, "soil_moisture": 55, "crop_health": "good",
|
| 156 |
-
# "water_action": 2, "rainfall": i % 5, "temperature": 35}
|
| 157 |
-
# for i in range(1, 31)
|
| 158 |
-
# ]
|
| 159 |
-
|
| 160 |
-
# print("Task 1 Score:", grade_task1(fake_7))
|
| 161 |
-
# print("Task 2 Score:", grade_task2(fake_14))
|
| 162 |
-
# print("Task 3 Score:", grade_task3(fake_30))
|
| 163 |
-
# print("Sample reward:", compute_reward(55, "good", 2, 0, 38))
|
| 164 |
-
|
| 165 |
# graders.py — reward functions and graders for all 3 tasks
|
| 166 |
|
| 167 |
def health_to_number(crop_health_str) -> int:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# graders.py — reward functions and graders for all 3 tasks
|
| 2 |
|
| 3 |
def health_to_number(crop_health_str) -> int:
|
my_env/server/__init__.py
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
-
# All rights reserved.
|
| 3 |
-
#
|
| 4 |
-
# This source code is licensed under the BSD-style license found in the
|
| 5 |
-
# LICENSE file in the root directory of this source tree.
|
| 6 |
-
|
| 7 |
-
"""Smart Farm Irrigation environment server components."""
|
| 8 |
-
|
| 9 |
-
from .my_env_environment import FarmEnvironment
|
| 10 |
-
|
| 11 |
-
__all__ = ["FarmEnvironment"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
my_env/server/__pycache__/__init__.cpython-313.pyc
DELETED
|
Binary file (335 Bytes)
|
|
|
my_env/server/__pycache__/__init__.cpython-314.pyc
DELETED
|
Binary file (327 Bytes)
|
|
|
my_env/server/__pycache__/app.cpython-313.pyc
DELETED
|
Binary file (10.2 kB)
|
|
|
my_env/server/__pycache__/app.cpython-314.pyc
DELETED
|
Binary file (8.53 kB)
|
|
|
my_env/server/__pycache__/my_env_environment.cpython-313.pyc
DELETED
|
Binary file (8.59 kB)
|
|
|
my_env/server/__pycache__/my_env_environment.cpython-314.pyc
DELETED
|
Binary file (8.89 kB)
|
|
|
my_env/server/app.py
DELETED
|
@@ -1,275 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
-
# All rights reserved.
|
| 3 |
-
#
|
| 4 |
-
# This source code is licensed under the BSD-style license found in the
|
| 5 |
-
# LICENSE file in the root directory of this source tree.
|
| 6 |
-
|
| 7 |
-
"""
|
| 8 |
-
FastAPI application for the Smart Farm Irrigation Environment.
|
| 9 |
-
|
| 10 |
-
Endpoints:
|
| 11 |
-
- POST /reset: Reset the environment
|
| 12 |
-
- POST /step: Execute an action
|
| 13 |
-
- GET /state: Get current environment state
|
| 14 |
-
- GET /schema: Get action/observation schemas
|
| 15 |
-
- WS /ws: WebSocket endpoint for persistent sessions
|
| 16 |
-
|
| 17 |
-
# Mandatory Hackathon Endpoints:
|
| 18 |
-
- GET /tasks: Returns list of all tasks + action schema
|
| 19 |
-
- POST /grader: Returns score after episode ends
|
| 20 |
-
- GET /baseline: Runs baseline agent, returns all 3 scores
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
from openenv.core.env_server.http_server import create_app
|
| 25 |
-
except Exception as e: # pragma: no cover
|
| 26 |
-
raise ImportError(
|
| 27 |
-
"openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
|
| 28 |
-
) from e
|
| 29 |
-
|
| 30 |
-
try:
|
| 31 |
-
from ..models import FarmAction, FarmObservation
|
| 32 |
-
from .my_env_environment import FarmEnvironment
|
| 33 |
-
except (ModuleNotFoundError, ImportError):
|
| 34 |
-
try:
|
| 35 |
-
from models import FarmAction, FarmObservation
|
| 36 |
-
from server.my_env_environment import FarmEnvironment
|
| 37 |
-
except ModuleNotFoundError:
|
| 38 |
-
import sys
|
| 39 |
-
import os
|
| 40 |
-
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 41 |
-
from models import FarmAction, FarmObservation
|
| 42 |
-
from server.my_env_environment import FarmEnvironment
|
| 43 |
-
|
| 44 |
-
from fastapi import Request
|
| 45 |
-
from fastapi.responses import JSONResponse,FileResponse,PlainTextResponse
|
| 46 |
-
from pathlib import Path
|
| 47 |
-
from fastapi.staticfiles import StaticFiles
|
| 48 |
-
import os
|
| 49 |
-
|
| 50 |
-
# Create the app with web interface and README integration
|
| 51 |
-
app = create_app(
|
| 52 |
-
FarmEnvironment,
|
| 53 |
-
FarmAction,
|
| 54 |
-
FarmObservation,
|
| 55 |
-
env_name="smart-farm-irrigation",
|
| 56 |
-
max_concurrent_envs=1,
|
| 57 |
-
)
|
| 58 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 59 |
-
|
| 60 |
-
# Serve the UI
|
| 61 |
-
@app.get("/ui")
|
| 62 |
-
async def serve_ui():
|
| 63 |
-
ui_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "smart-farm-ui.html")
|
| 64 |
-
return FileResponse(ui_path, media_type="text/html")
|
| 65 |
-
|
| 66 |
-
@app.get("/openenv.yaml", response_class=PlainTextResponse)
|
| 67 |
-
async def serve_openenv_spec():
|
| 68 |
-
"""Serve the OpenEnv spec file — required for validation."""
|
| 69 |
-
possible_paths = [
|
| 70 |
-
Path(__file__).parent.parent / "openenv.yaml", # root (server/../openenv.yaml)
|
| 71 |
-
Path("/app/openenv.yaml"), # Docker absolute path
|
| 72 |
-
Path("openenv.yaml"), # working directory
|
| 73 |
-
]
|
| 74 |
-
for p in possible_paths:
|
| 75 |
-
if p.exists():
|
| 76 |
-
return PlainTextResponse(content=p.read_text(), media_type="text/yaml")
|
| 77 |
-
return PlainTextResponse(
|
| 78 |
-
content="openenv.yaml not found", status_code=404
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
app.add_middleware(
|
| 82 |
-
CORSMiddleware,
|
| 83 |
-
allow_origins=["*"], # In production, replace * with your frontend URL
|
| 84 |
-
allow_methods=["*"],
|
| 85 |
-
allow_headers=["*"],
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
# MANDATORY ENDPOINT 1 — /tasks
|
| 89 |
-
# Returns list of tasks and action schema
|
| 90 |
-
@app.get("/tasks")
|
| 91 |
-
async def get_tasks():
|
| 92 |
-
"""
|
| 93 |
-
Returns all 3 tasks and the action schema.
|
| 94 |
-
Mandatory endpoint for hackathon submission.
|
| 95 |
-
"""
|
| 96 |
-
try:
|
| 97 |
-
from tasks import get_all_tasks
|
| 98 |
-
except ImportError:
|
| 99 |
-
try:
|
| 100 |
-
from my_env.tasks import get_all_tasks
|
| 101 |
-
except ImportError:
|
| 102 |
-
import sys, os
|
| 103 |
-
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 104 |
-
from tasks import get_all_tasks
|
| 105 |
-
|
| 106 |
-
return JSONResponse(content=get_all_tasks())
|
| 107 |
-
|
| 108 |
-
# MANDATORY ENDPOINT 2 — /grader
|
| 109 |
-
# Returns score after episode ends
|
| 110 |
-
@app.post("/grader")
|
| 111 |
-
async def grade_episode(request: Request):
|
| 112 |
-
"""
|
| 113 |
-
Grades a completed episode and returns score.
|
| 114 |
-
|
| 115 |
-
Expected request body:
|
| 116 |
-
{
|
| 117 |
-
"task_id": 1,
|
| 118 |
-
"episode_history": [
|
| 119 |
-
{
|
| 120 |
-
"day": 1,
|
| 121 |
-
"soil_moisture": 55.0,
|
| 122 |
-
"crop_health": "good",
|
| 123 |
-
"water_action": 2,
|
| 124 |
-
"rainfall": 0.0
|
| 125 |
-
},
|
| 126 |
-
...
|
| 127 |
-
]
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
Returns score between 0.0 and 1.0
|
| 131 |
-
"""
|
| 132 |
-
try:
|
| 133 |
-
from graders import grade_task1, grade_task2, grade_task3
|
| 134 |
-
except ImportError:
|
| 135 |
-
try:
|
| 136 |
-
from my_env.graders import grade_task1, grade_task2, grade_task3
|
| 137 |
-
except ImportError:
|
| 138 |
-
import sys, os
|
| 139 |
-
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 140 |
-
from graders import grade_task1, grade_task2, grade_task3
|
| 141 |
-
|
| 142 |
-
try:
|
| 143 |
-
body = await request.json()
|
| 144 |
-
task_id = body.get("task_id", 1)
|
| 145 |
-
episode_history = body.get("episode_history", [])
|
| 146 |
-
|
| 147 |
-
# Select correct grader
|
| 148 |
-
graders = {
|
| 149 |
-
1: grade_task1,
|
| 150 |
-
2: grade_task2,
|
| 151 |
-
3: grade_task3,
|
| 152 |
-
}
|
| 153 |
-
|
| 154 |
-
if task_id not in graders:
|
| 155 |
-
return JSONResponse(
|
| 156 |
-
content={"error": f"Invalid task_id: {task_id}. Must be 1, 2, or 3"},
|
| 157 |
-
status_code=400
|
| 158 |
-
)
|
| 159 |
-
|
| 160 |
-
score = graders[task_id](episode_history)
|
| 161 |
-
|
| 162 |
-
return JSONResponse(content={
|
| 163 |
-
"task_id": task_id,
|
| 164 |
-
"score": score,
|
| 165 |
-
"min_score": 0.0,
|
| 166 |
-
"max_score": 1.0,
|
| 167 |
-
})
|
| 168 |
-
|
| 169 |
-
except Exception as e:
|
| 170 |
-
return JSONResponse(
|
| 171 |
-
content={"error": str(e)},
|
| 172 |
-
status_code=500
|
| 173 |
-
)
|
| 174 |
-
|
| 175 |
-
# MANDATORY ENDPOINT 3 — /baseline
|
| 176 |
-
# Runs baseline agent, returns all scores
|
| 177 |
-
@app.get("/baseline")
|
| 178 |
-
async def run_baseline(city: str = "Indore"):
|
| 179 |
-
"""
|
| 180 |
-
Runs the baseline rule-based agent through all 3 tasks
|
| 181 |
-
and returns reproducible scores.
|
| 182 |
-
|
| 183 |
-
Query params:
|
| 184 |
-
city: City name for weather data (default: Indore)
|
| 185 |
-
|
| 186 |
-
Returns scores for all 3 tasks + average score
|
| 187 |
-
"""
|
| 188 |
-
try:
|
| 189 |
-
from baseline import main as run_baseline_agent
|
| 190 |
-
except ImportError:
|
| 191 |
-
try:
|
| 192 |
-
from my_env.baseline import main as run_baseline_agent
|
| 193 |
-
except ImportError:
|
| 194 |
-
import sys, os
|
| 195 |
-
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 196 |
-
from baseline import main as run_baseline_agent
|
| 197 |
-
|
| 198 |
-
try:
|
| 199 |
-
results = run_baseline_agent(city=city)
|
| 200 |
-
|
| 201 |
-
# Format results for response
|
| 202 |
-
scores = {}
|
| 203 |
-
for result in results:
|
| 204 |
-
scores[f"task_{result['task_id']}"] = {
|
| 205 |
-
"name": result["task_name"],
|
| 206 |
-
"score": result["score"],
|
| 207 |
-
"steps_completed": result["steps_completed"],
|
| 208 |
-
}
|
| 209 |
-
|
| 210 |
-
avg = sum(r["score"] for r in results) / len(results)
|
| 211 |
-
|
| 212 |
-
return JSONResponse(content={
|
| 213 |
-
"city": city,
|
| 214 |
-
"agent": "Simple Rule-Based Agent",
|
| 215 |
-
"scores": scores,
|
| 216 |
-
"average_score": round(avg, 2),
|
| 217 |
-
"status": "success"
|
| 218 |
-
})
|
| 219 |
-
|
| 220 |
-
except Exception as e:
|
| 221 |
-
return JSONResponse(
|
| 222 |
-
content={"error": str(e)},
|
| 223 |
-
status_code=500
|
| 224 |
-
)
|
| 225 |
-
|
| 226 |
-
@app.post("/inference-step")
|
| 227 |
-
async def inference_step(request: Request):
|
| 228 |
-
"""
|
| 229 |
-
Single step LLM decision for UI.
|
| 230 |
-
"""
|
| 231 |
-
try:
|
| 232 |
-
from inference import llm_decide
|
| 233 |
-
except ImportError:
|
| 234 |
-
import sys, os
|
| 235 |
-
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 236 |
-
from inference import llm_decide
|
| 237 |
-
|
| 238 |
-
try:
|
| 239 |
-
body = await request.json()
|
| 240 |
-
observation = body.get("observation", {})
|
| 241 |
-
task_id = body.get("task_id", 1)
|
| 242 |
-
day = body.get("day", 1)
|
| 243 |
-
max_days = body.get("max_days", 7)
|
| 244 |
-
|
| 245 |
-
action, reason = llm_decide(observation, task_id, day, max_days)
|
| 246 |
-
|
| 247 |
-
return JSONResponse(content={
|
| 248 |
-
"action": action,
|
| 249 |
-
"reason": reason
|
| 250 |
-
})
|
| 251 |
-
|
| 252 |
-
except Exception as e:
|
| 253 |
-
return JSONResponse(
|
| 254 |
-
content={"error": str(e)},
|
| 255 |
-
status_code=500
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
def main(host: str = "0.0.0.0", port: int = 7860):
|
| 259 |
-
"""
|
| 260 |
-
Entry point for direct execution via uv run or python -m.
|
| 261 |
-
"""
|
| 262 |
-
import uvicorn
|
| 263 |
-
uvicorn.run(app, host=host, port=port)
|
| 264 |
-
|
| 265 |
-
# Mount root directory so openenv.yaml is accessible
|
| 266 |
-
_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 267 |
-
app.mount("/static", StaticFiles(directory=_root), name="static")
|
| 268 |
-
|
| 269 |
-
if __name__ == "__main__":
|
| 270 |
-
import argparse
|
| 271 |
-
|
| 272 |
-
parser = argparse.ArgumentParser()
|
| 273 |
-
parser.add_argument("--port", type=int, default=8000)
|
| 274 |
-
args = parser.parse_args()
|
| 275 |
-
main(port=args.port)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
my_env/server/my_env_environment.py
DELETED
|
@@ -1,242 +0,0 @@
|
|
| 1 |
-
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
-
# All rights reserved.
|
| 3 |
-
#
|
| 4 |
-
# This source code is licensed under the BSD-style license found in the
|
| 5 |
-
# LICENSE file in the root directory of this source tree.
|
| 6 |
-
|
| 7 |
-
"""
|
| 8 |
-
Smart Farm Irrigation Environment Implementation.
|
| 9 |
-
|
| 10 |
-
A real-world environment where an AI agent manages crop irrigation
|
| 11 |
-
by deciding how much water to give crops each day based on:
|
| 12 |
-
- Weather conditions (temperature, rainfall) from real Weather API
|
| 13 |
-
- Soil moisture (from sensor or auto-calculated)
|
| 14 |
-
- Crop health (user input)
|
| 15 |
-
- Crop stage (auto-managed by code)
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
from uuid import uuid4
|
| 19 |
-
|
| 20 |
-
from openenv.core.env_server.interfaces import Environment
|
| 21 |
-
from openenv.core.env_server.types import State
|
| 22 |
-
|
| 23 |
-
try:
|
| 24 |
-
from ..models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 25 |
-
from ..weather import WeatherService
|
| 26 |
-
except ImportError:
|
| 27 |
-
from models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 28 |
-
from weather import WeatherService
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class FarmEnvironment(Environment):
|
| 32 |
-
"""
|
| 33 |
-
Smart Farm Irrigation Environment.
|
| 34 |
-
|
| 35 |
-
The AI agent decides how much to water crops every day.
|
| 36 |
-
The environment simulates soil moisture, crop health,
|
| 37 |
-
weather conditions, and crop growth stages.
|
| 38 |
-
"""
|
| 39 |
-
|
| 40 |
-
SUPPORTS_CONCURRENT_SESSIONS: bool = True
|
| 41 |
-
|
| 42 |
-
def __init__(self):
|
| 43 |
-
"""Initialize the farm environment with default values."""
|
| 44 |
-
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 45 |
-
|
| 46 |
-
# --- Weather Service ---
|
| 47 |
-
self._weather_service = WeatherService()
|
| 48 |
-
self._city = "Indore"
|
| 49 |
-
|
| 50 |
-
# --- Farm State Variables ---
|
| 51 |
-
self._day = 1
|
| 52 |
-
self._soil_moisture = 30.0
|
| 53 |
-
self._crop_health = CropHealthStatus.FAIR
|
| 54 |
-
self._temperature = 30.0
|
| 55 |
-
self._rainfall = 0.0
|
| 56 |
-
self._crop_stage = CropStage.SEEDLING
|
| 57 |
-
self._sensor_moisture = None
|
| 58 |
-
|
| 59 |
-
def reset(
|
| 60 |
-
self,
|
| 61 |
-
city: str = "Indore",
|
| 62 |
-
sensor_moisture: float = None,
|
| 63 |
-
crop_health: str = "fair"
|
| 64 |
-
) -> FarmObservation:
|
| 65 |
-
"""
|
| 66 |
-
Reset the farm to Day 1 fresh state.
|
| 67 |
-
Fetches real weather data for the given city.
|
| 68 |
-
|
| 69 |
-
Args:
|
| 70 |
-
city: City name for weather data
|
| 71 |
-
sensor_moisture: Soil moisture from sensor (optional)
|
| 72 |
-
crop_health: User selected crop health status
|
| 73 |
-
"""
|
| 74 |
-
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 75 |
-
|
| 76 |
-
# --- Fetch Real Weather Data ---
|
| 77 |
-
self._city = city
|
| 78 |
-
weather = self._weather_service.get_weather(city)
|
| 79 |
-
self._temperature = weather["temperature"]
|
| 80 |
-
self._rainfall = weather["rainfall"]
|
| 81 |
-
|
| 82 |
-
print(f"Weather for {city}: {self._temperature}C, {self._rainfall}mm rain")
|
| 83 |
-
|
| 84 |
-
# --- Soil Moisture ---
|
| 85 |
-
if sensor_moisture is not None:
|
| 86 |
-
# User has a sensor — use their reading
|
| 87 |
-
self._soil_moisture = sensor_moisture
|
| 88 |
-
print(f"Soil moisture from sensor: {self._soil_moisture}%")
|
| 89 |
-
else:
|
| 90 |
-
# No sensor — calculate from weather
|
| 91 |
-
self._soil_moisture = self._weather_service.calculate_soil_moisture(
|
| 92 |
-
current_moisture=50.0,
|
| 93 |
-
temperature=self._temperature,
|
| 94 |
-
rainfall=self._rainfall
|
| 95 |
-
)
|
| 96 |
-
print(f"Soil moisture calculated: {self._soil_moisture}%")
|
| 97 |
-
|
| 98 |
-
# --- Crop Health from User ---
|
| 99 |
-
try:
|
| 100 |
-
self._crop_health = CropHealthStatus(crop_health)
|
| 101 |
-
except ValueError:
|
| 102 |
-
self._crop_health = CropHealthStatus.FAIR
|
| 103 |
-
|
| 104 |
-
# --- Reset Other Values ---
|
| 105 |
-
self._day = 1
|
| 106 |
-
self._crop_stage = CropStage.SEEDLING
|
| 107 |
-
|
| 108 |
-
return FarmObservation(
|
| 109 |
-
temperature=self._temperature,
|
| 110 |
-
rainfall=self._rainfall,
|
| 111 |
-
soil_moisture=self._soil_moisture,
|
| 112 |
-
crop_health=self._crop_health,
|
| 113 |
-
day_number=self._day,
|
| 114 |
-
crop_stage=self._crop_stage,
|
| 115 |
-
done=False,
|
| 116 |
-
reward=0.0,
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
def step(self, action: FarmAction) -> FarmObservation:
|
| 120 |
-
"""
|
| 121 |
-
Execute one day of farming.
|
| 122 |
-
AI provides water_amount, environment updates accordingly.
|
| 123 |
-
"""
|
| 124 |
-
self._state.step_count += 1
|
| 125 |
-
|
| 126 |
-
# --- Water Amount Mapping ---
|
| 127 |
-
water_map = {
|
| 128 |
-
"none": 0,
|
| 129 |
-
"low": 10,
|
| 130 |
-
"medium": 25,
|
| 131 |
-
"high": 50,
|
| 132 |
-
}
|
| 133 |
-
water_added = water_map.get(action.water_amount.value, 0)
|
| 134 |
-
|
| 135 |
-
# --- Use real historical weather for each day ---
|
| 136 |
-
weather = self._weather_service.get_historical_weather(
|
| 137 |
-
self._city, self._day
|
| 138 |
-
)
|
| 139 |
-
self._temperature = weather["temperature"]
|
| 140 |
-
self._rainfall = weather["rainfall"]
|
| 141 |
-
|
| 142 |
-
# --- Update Soil Moisture ---
|
| 143 |
-
if self._sensor_moisture is not None:
|
| 144 |
-
# sensor user — just add water and subtract evaporation
|
| 145 |
-
evaporation = (self._temperature / 100) * 10
|
| 146 |
-
self._soil_moisture = self._soil_moisture + water_added - evaporation
|
| 147 |
-
else:
|
| 148 |
-
# no sensor — use weather calculator
|
| 149 |
-
self._soil_moisture = self._weather_service.calculate_soil_moisture(
|
| 150 |
-
current_moisture=self._soil_moisture + water_added,
|
| 151 |
-
temperature=self._temperature,
|
| 152 |
-
rainfall=self._rainfall
|
| 153 |
-
)
|
| 154 |
-
|
| 155 |
-
# Keep moisture in valid range 0-100
|
| 156 |
-
self._soil_moisture = max(0.0, min(100.0, self._soil_moisture))
|
| 157 |
-
|
| 158 |
-
# --- Update Crop Health based on moisture ---
|
| 159 |
-
health_order = ["poor", "fair", "good", "excellent"]
|
| 160 |
-
current_idx = health_order.index(self._crop_health.value)
|
| 161 |
-
|
| 162 |
-
if self._soil_moisture < 20 or self._soil_moisture > 90:
|
| 163 |
-
# Very wrong moisture — health degrades
|
| 164 |
-
new_idx = max(0, current_idx - 1)
|
| 165 |
-
self._crop_health = CropHealthStatus(health_order[new_idx])
|
| 166 |
-
elif 40 <= self._soil_moisture <= 75:
|
| 167 |
-
# Good moisture — health improves
|
| 168 |
-
new_idx = min(3, current_idx + 1)
|
| 169 |
-
self._crop_health = CropHealthStatus(health_order[new_idx])
|
| 170 |
-
# else: moisture okay but not ideal — health stays same
|
| 171 |
-
|
| 172 |
-
# --- Advance Day ---
|
| 173 |
-
self._day += 1
|
| 174 |
-
|
| 175 |
-
# --- Auto Update Crop Stage based on day ---
|
| 176 |
-
if self._day <= 10:
|
| 177 |
-
self._crop_stage = CropStage.SEEDLING
|
| 178 |
-
elif self._day <= 20:
|
| 179 |
-
self._crop_stage = CropStage.GROWING
|
| 180 |
-
else:
|
| 181 |
-
self._crop_stage = CropStage.MATURE
|
| 182 |
-
|
| 183 |
-
# --- Calculate Reward ---
|
| 184 |
-
reward = self._calculate_reward(water_added)
|
| 185 |
-
|
| 186 |
-
# --- Is episode done? ---
|
| 187 |
-
done = self._day > 30
|
| 188 |
-
|
| 189 |
-
return FarmObservation(
|
| 190 |
-
temperature=self._temperature,
|
| 191 |
-
rainfall=self._rainfall,
|
| 192 |
-
soil_moisture=self._soil_moisture,
|
| 193 |
-
crop_health=self._crop_health,
|
| 194 |
-
day_number=min(self._day, 30),
|
| 195 |
-
crop_stage=self._crop_stage,
|
| 196 |
-
done=done,
|
| 197 |
-
reward=reward,
|
| 198 |
-
)
|
| 199 |
-
|
| 200 |
-
def _calculate_reward(self, water_added: float) -> float:
|
| 201 |
-
"""
|
| 202 |
-
Calculate reward based on soil moisture and water usage.
|
| 203 |
-
Returns value between -1.0 and 1.0
|
| 204 |
-
"""
|
| 205 |
-
# Ideal moisture ranges per crop stage
|
| 206 |
-
ideal_ranges = {
|
| 207 |
-
CropStage.SEEDLING: (40, 70),
|
| 208 |
-
CropStage.GROWING: (45, 70),
|
| 209 |
-
CropStage.MATURE: (35, 60),
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
low, high = ideal_ranges[self._crop_stage]
|
| 213 |
-
|
| 214 |
-
# Perfect moisture range
|
| 215 |
-
if low <= self._soil_moisture <= high:
|
| 216 |
-
reward = 1.0
|
| 217 |
-
|
| 218 |
-
# Acceptable but not ideal
|
| 219 |
-
elif (low - 10) <= self._soil_moisture <= (high + 10):
|
| 220 |
-
reward = 0.5
|
| 221 |
-
|
| 222 |
-
# Too dry
|
| 223 |
-
elif self._soil_moisture < 20:
|
| 224 |
-
reward = -1.0
|
| 225 |
-
|
| 226 |
-
# Too wet
|
| 227 |
-
elif self._soil_moisture > 90:
|
| 228 |
-
reward = -0.5
|
| 229 |
-
|
| 230 |
-
else:
|
| 231 |
-
reward = 0.0
|
| 232 |
-
|
| 233 |
-
# Penalize watering on rainy days (water waste)
|
| 234 |
-
if self._rainfall > 15 and water_added > 0:
|
| 235 |
-
reward -= 0.3
|
| 236 |
-
|
| 237 |
-
return round(max(-1.0, min(1.0, reward)), 2)
|
| 238 |
-
|
| 239 |
-
@property
|
| 240 |
-
def state(self) -> State:
|
| 241 |
-
"""Return current environment state."""
|
| 242 |
-
return self._state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
my_env/server/requirements.txt
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
openenv[core]>=0.2.0
|
| 2 |
-
fastapi>=0.115.0
|
| 3 |
-
uvicorn>=0.24.0
|
| 4 |
-
requests>=2.32.0
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
openenv.yaml
CHANGED
|
@@ -95,5 +95,4 @@ reward:
|
|
| 95 |
- water_conservation_bonus
|
| 96 |
- rain_day_penalty
|
| 97 |
- crop_stage_compliance
|
| 98 |
-
- final_yield_score
|
| 99 |
-
|
|
|
|
| 95 |
- water_conservation_bonus
|
| 96 |
- rain_day_penalty
|
| 97 |
- crop_stage_compliance
|
| 98 |
+
- final_yield_score
|
|
|
openenv_my_env.egg-info/SOURCES.txt
CHANGED
|
@@ -7,12 +7,12 @@ my_env/graders.py
|
|
| 7 |
my_env/models.py
|
| 8 |
my_env/tasks.py
|
| 9 |
my_env/weather.py
|
| 10 |
-
my_env/server/__init__.py
|
| 11 |
-
my_env/server/app.py
|
| 12 |
-
my_env/server/my_env_environment.py
|
| 13 |
openenv_my_env.egg-info/PKG-INFO
|
| 14 |
openenv_my_env.egg-info/SOURCES.txt
|
| 15 |
openenv_my_env.egg-info/dependency_links.txt
|
| 16 |
openenv_my_env.egg-info/entry_points.txt
|
| 17 |
openenv_my_env.egg-info/requires.txt
|
| 18 |
-
openenv_my_env.egg-info/top_level.txt
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
my_env/models.py
|
| 8 |
my_env/tasks.py
|
| 9 |
my_env/weather.py
|
|
|
|
|
|
|
|
|
|
| 10 |
openenv_my_env.egg-info/PKG-INFO
|
| 11 |
openenv_my_env.egg-info/SOURCES.txt
|
| 12 |
openenv_my_env.egg-info/dependency_links.txt
|
| 13 |
openenv_my_env.egg-info/entry_points.txt
|
| 14 |
openenv_my_env.egg-info/requires.txt
|
| 15 |
+
openenv_my_env.egg-info/top_level.txt
|
| 16 |
+
server/__init__.py
|
| 17 |
+
server/app.py
|
| 18 |
+
server/my_env_environment.py
|
openenv_my_env.egg-info/entry_points.txt
CHANGED
|
@@ -1,2 +1,2 @@
|
|
| 1 |
[console_scripts]
|
| 2 |
-
server =
|
|
|
|
| 1 |
[console_scripts]
|
| 2 |
+
server = server.app:main
|
openenv_my_env.egg-info/top_level.txt
CHANGED
|
@@ -1 +1,2 @@
|
|
| 1 |
my_env
|
|
|
|
|
|
| 1 |
my_env
|
| 2 |
+
server
|
pyproject.toml
CHANGED
|
@@ -37,9 +37,9 @@ dev = [
|
|
| 37 |
[project.scripts]
|
| 38 |
# Server entry point - enables running via: uv run --project . server
|
| 39 |
# or: python -m my_env.server.app
|
| 40 |
-
server = "
|
| 41 |
|
| 42 |
[tool.setuptools]
|
| 43 |
include-package-data = true
|
| 44 |
-
packages = ["my_env",
|
| 45 |
-
package-dir = { "my_env" = "my_env", "
|
|
|
|
| 37 |
[project.scripts]
|
| 38 |
# Server entry point - enables running via: uv run --project . server
|
| 39 |
# or: python -m my_env.server.app
|
| 40 |
+
server = "server.app:main"
|
| 41 |
|
| 42 |
[tool.setuptools]
|
| 43 |
include-package-data = true
|
| 44 |
+
packages = ["my_env","server"]
|
| 45 |
+
package-dir = { "my_env" = "my_env", "server" = "server" }
|
server/__pycache__/app.cpython-313.pyc
CHANGED
|
Binary files a/server/__pycache__/app.cpython-313.pyc and b/server/__pycache__/app.cpython-313.pyc differ
|
|
|
server/__pycache__/my_env_environment.cpython-313.pyc
CHANGED
|
Binary files a/server/__pycache__/my_env_environment.cpython-313.pyc and b/server/__pycache__/my_env_environment.cpython-313.pyc differ
|
|
|
server/app.py
CHANGED
|
@@ -19,16 +19,20 @@ Endpoints:
|
|
| 19 |
- POST /grader: Returns score after episode ends
|
| 20 |
- GET /baseline: Runs baseline agent, returns all 3 scores
|
| 21 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
try:
|
| 24 |
from openenv.core.env_server.http_server import create_app
|
| 25 |
-
except Exception as e:
|
| 26 |
raise ImportError(
|
| 27 |
"openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
|
| 28 |
) from e
|
| 29 |
|
| 30 |
try:
|
| 31 |
-
from .
|
| 32 |
from .my_env_environment import FarmEnvironment
|
| 33 |
except (ModuleNotFoundError, ImportError):
|
| 34 |
try:
|
|
@@ -45,7 +49,6 @@ from fastapi import Request
|
|
| 45 |
from fastapi.responses import JSONResponse,FileResponse,PlainTextResponse
|
| 46 |
|
| 47 |
from fastapi.staticfiles import StaticFiles
|
| 48 |
-
import os
|
| 49 |
|
| 50 |
# Create the app with web interface and README integration
|
| 51 |
app = create_app(
|
|
@@ -99,7 +102,7 @@ async def get_tasks():
|
|
| 99 |
except ImportError:
|
| 100 |
import sys, os
|
| 101 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 102 |
-
from tasks import get_all_tasks
|
| 103 |
|
| 104 |
return JSONResponse(content=get_all_tasks())
|
| 105 |
|
|
@@ -135,7 +138,7 @@ async def grade_episode(request: Request):
|
|
| 135 |
except ImportError:
|
| 136 |
import sys, os
|
| 137 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 138 |
-
from graders import grade_task1, grade_task2, grade_task3
|
| 139 |
|
| 140 |
try:
|
| 141 |
body = await request.json()
|
|
@@ -201,7 +204,7 @@ async def run_baseline(city: str = "Indore"):
|
|
| 201 |
except ImportError:
|
| 202 |
import sys, os
|
| 203 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 204 |
-
from baseline import main as run_baseline_agent
|
| 205 |
|
| 206 |
try:
|
| 207 |
results = run_baseline_agent(city=city)
|
|
@@ -275,10 +278,4 @@ _root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
| 275 |
app.mount("/static", StaticFiles(directory=_root), name="static")
|
| 276 |
|
| 277 |
if __name__ == "__main__":
|
| 278 |
-
# import argparse
|
| 279 |
-
|
| 280 |
-
# parser = argparse.ArgumentParser()
|
| 281 |
-
# parser.add_argument("--port", type=int, default=8000)
|
| 282 |
-
# args = parser.parse_args()
|
| 283 |
-
# main(port=args.port)
|
| 284 |
main()
|
|
|
|
| 19 |
- POST /grader: Returns score after episode ends
|
| 20 |
- GET /baseline: Runs baseline agent, returns all 3 scores
|
| 21 |
"""
|
| 22 |
+
import sys
|
| 23 |
+
import os
|
| 24 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 25 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "my_env"))
|
| 26 |
|
| 27 |
try:
|
| 28 |
from openenv.core.env_server.http_server import create_app
|
| 29 |
+
except Exception as e:
|
| 30 |
raise ImportError(
|
| 31 |
"openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
|
| 32 |
) from e
|
| 33 |
|
| 34 |
try:
|
| 35 |
+
from my_env.models import FarmAction, FarmObservation
|
| 36 |
from .my_env_environment import FarmEnvironment
|
| 37 |
except (ModuleNotFoundError, ImportError):
|
| 38 |
try:
|
|
|
|
| 49 |
from fastapi.responses import JSONResponse,FileResponse,PlainTextResponse
|
| 50 |
|
| 51 |
from fastapi.staticfiles import StaticFiles
|
|
|
|
| 52 |
|
| 53 |
# Create the app with web interface and README integration
|
| 54 |
app = create_app(
|
|
|
|
| 102 |
except ImportError:
|
| 103 |
import sys, os
|
| 104 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 105 |
+
from my_env.tasks import get_all_tasks
|
| 106 |
|
| 107 |
return JSONResponse(content=get_all_tasks())
|
| 108 |
|
|
|
|
| 138 |
except ImportError:
|
| 139 |
import sys, os
|
| 140 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 141 |
+
from my_env.graders import grade_task1, grade_task2, grade_task3
|
| 142 |
|
| 143 |
try:
|
| 144 |
body = await request.json()
|
|
|
|
| 204 |
except ImportError:
|
| 205 |
import sys, os
|
| 206 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 207 |
+
from my_env.baseline import main as run_baseline_agent
|
| 208 |
|
| 209 |
try:
|
| 210 |
results = run_baseline_agent(city=city)
|
|
|
|
| 278 |
app.mount("/static", StaticFiles(directory=_root), name="static")
|
| 279 |
|
| 280 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
main()
|
server/my_env_environment.py
CHANGED
|
@@ -1,245 +1,19 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
-
#
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# from uuid import uuid4
|
| 19 |
-
|
| 20 |
-
# from openenv.core.env_server.interfaces import Environment
|
| 21 |
-
# from openenv.core.env_server.types import State
|
| 22 |
-
|
| 23 |
-
# try:
|
| 24 |
-
# from ..models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 25 |
-
# from ..weather import WeatherService
|
| 26 |
-
# except ImportError:
|
| 27 |
-
# from models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 28 |
-
# from weather import WeatherService
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# class FarmEnvironment(Environment):
|
| 32 |
-
# """
|
| 33 |
-
# Smart Farm Irrigation Environment.
|
| 34 |
-
|
| 35 |
-
# The AI agent decides how much to water crops every day.
|
| 36 |
-
# The environment simulates soil moisture, crop health,
|
| 37 |
-
# weather conditions, and crop growth stages.
|
| 38 |
-
# """
|
| 39 |
-
|
| 40 |
-
# SUPPORTS_CONCURRENT_SESSIONS: bool = True
|
| 41 |
-
|
| 42 |
-
# def __init__(self):
|
| 43 |
-
# """Initialize the farm environment with default values."""
|
| 44 |
-
# self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 45 |
-
|
| 46 |
-
# # --- Weather Service ---
|
| 47 |
-
# self._weather_service = WeatherService()
|
| 48 |
-
# self._city = "Indore"
|
| 49 |
-
|
| 50 |
-
# # --- Farm State Variables ---
|
| 51 |
-
# self._day = 1
|
| 52 |
-
# self._soil_moisture = 30.0
|
| 53 |
-
# self._crop_health = CropHealthStatus.FAIR
|
| 54 |
-
# self._temperature = 30.0
|
| 55 |
-
# self._rainfall = 0.0
|
| 56 |
-
# self._crop_stage = CropStage.SEEDLING
|
| 57 |
-
# self._sensor_moisture = None
|
| 58 |
-
|
| 59 |
-
# def reset(
|
| 60 |
-
# self,
|
| 61 |
-
# city: str = "Indore",
|
| 62 |
-
# sensor_moisture: float = None,
|
| 63 |
-
# crop_health: str = "fair"
|
| 64 |
-
# ) -> FarmObservation:
|
| 65 |
-
# """
|
| 66 |
-
# Reset the farm to Day 1 fresh state.
|
| 67 |
-
# Fetches real weather data for the given city.
|
| 68 |
-
|
| 69 |
-
# Args:
|
| 70 |
-
# city: City name for weather data
|
| 71 |
-
# sensor_moisture: Soil moisture from sensor (optional)
|
| 72 |
-
# crop_health: User selected crop health status
|
| 73 |
-
# """
|
| 74 |
-
# self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 75 |
-
|
| 76 |
-
# # --- Fetch Real Weather Data ---
|
| 77 |
-
# self._city = city
|
| 78 |
-
# weather = self._weather_service.get_weather(city)
|
| 79 |
-
# self._temperature = weather["temperature"]
|
| 80 |
-
# self._rainfall = weather["rainfall"]
|
| 81 |
-
|
| 82 |
-
# print(f"Weather for {city}: {self._temperature}C, {self._rainfall}mm rain")
|
| 83 |
-
|
| 84 |
-
# # --- Soil Moisture ---
|
| 85 |
-
# if sensor_moisture is not None:
|
| 86 |
-
# # User has a sensor — use their reading
|
| 87 |
-
# self._soil_moisture = sensor_moisture
|
| 88 |
-
# print(f"Soil moisture from sensor: {self._soil_moisture}%")
|
| 89 |
-
# else:
|
| 90 |
-
# # No sensor — calculate from weather
|
| 91 |
-
# self._soil_moisture = self._weather_service.calculate_soil_moisture(
|
| 92 |
-
# current_moisture=50.0,
|
| 93 |
-
# temperature=self._temperature,
|
| 94 |
-
# rainfall=self._rainfall
|
| 95 |
-
# )
|
| 96 |
-
# print(f"Soil moisture calculated: {self._soil_moisture}%")
|
| 97 |
-
|
| 98 |
-
# # --- Crop Health from User ---
|
| 99 |
-
# try:
|
| 100 |
-
# self._crop_health = CropHealthStatus(crop_health)
|
| 101 |
-
# except ValueError:
|
| 102 |
-
# self._crop_health = CropHealthStatus.FAIR
|
| 103 |
-
|
| 104 |
-
# # --- Reset Other Values ---
|
| 105 |
-
# self._day = 1
|
| 106 |
-
# self._crop_stage = CropStage.SEEDLING
|
| 107 |
-
|
| 108 |
-
# return FarmObservation(
|
| 109 |
-
# temperature=self._temperature,
|
| 110 |
-
# rainfall=self._rainfall,
|
| 111 |
-
# soil_moisture=self._soil_moisture,
|
| 112 |
-
# crop_health=self._crop_health,
|
| 113 |
-
# day_number=self._day,
|
| 114 |
-
# crop_stage=self._crop_stage,
|
| 115 |
-
# done=False,
|
| 116 |
-
# reward=0.0,
|
| 117 |
-
# )
|
| 118 |
-
|
| 119 |
-
# def step(self, action: FarmAction) -> FarmObservation:
|
| 120 |
-
# """
|
| 121 |
-
# Execute one day of farming.
|
| 122 |
-
# AI provides water_amount, environment updates accordingly.
|
| 123 |
-
# """
|
| 124 |
-
# self._state.step_count += 1
|
| 125 |
-
|
| 126 |
-
# # --- Water Amount Mapping ---
|
| 127 |
-
# water_map = {
|
| 128 |
-
# "none": 0,
|
| 129 |
-
# "low": 10,
|
| 130 |
-
# "medium": 25,
|
| 131 |
-
# "high": 50,
|
| 132 |
-
# }
|
| 133 |
-
# water_added = water_map.get(action.water_amount.value, 0)
|
| 134 |
-
|
| 135 |
-
# # --- Use real historical weather for each day ---
|
| 136 |
-
# weather = self._weather_service.get_historical_weather(
|
| 137 |
-
# self._city, self._day
|
| 138 |
-
# )
|
| 139 |
-
# self._temperature = weather["temperature"]
|
| 140 |
-
# self._rainfall = weather["rainfall"]
|
| 141 |
-
|
| 142 |
-
# # --- Update Soil Moisture ---
|
| 143 |
-
# if self._sensor_moisture is not None:
|
| 144 |
-
# # sensor user — just add water and subtract evaporation
|
| 145 |
-
# evaporation = (self._temperature / 100) * 10
|
| 146 |
-
# self._soil_moisture = self._soil_moisture + water_added - evaporation
|
| 147 |
-
# else:
|
| 148 |
-
# # no sensor — use weather calculator
|
| 149 |
-
# self._soil_moisture = self._weather_service.calculate_soil_moisture(
|
| 150 |
-
# current_moisture=self._soil_moisture + water_added,
|
| 151 |
-
# temperature=self._temperature,
|
| 152 |
-
# rainfall=self._rainfall
|
| 153 |
-
# )
|
| 154 |
-
|
| 155 |
-
# # Keep moisture in valid range 0-100
|
| 156 |
-
# self._soil_moisture = max(0.0, min(100.0, self._soil_moisture))
|
| 157 |
-
|
| 158 |
-
# # --- Update Crop Health based on moisture ---
|
| 159 |
-
# health_order = ["poor", "fair", "good", "excellent"]
|
| 160 |
-
# current_idx = health_order.index(self._crop_health.value)
|
| 161 |
-
|
| 162 |
-
# if self._soil_moisture < 20 or self._soil_moisture > 90:
|
| 163 |
-
# # Very wrong moisture — health degrades
|
| 164 |
-
# new_idx = max(0, current_idx - 1)
|
| 165 |
-
# self._crop_health = CropHealthStatus(health_order[new_idx])
|
| 166 |
-
# elif 40 <= self._soil_moisture <= 75:
|
| 167 |
-
# # Good moisture — health improves
|
| 168 |
-
# new_idx = min(3, current_idx + 1)
|
| 169 |
-
# self._crop_health = CropHealthStatus(health_order[new_idx])
|
| 170 |
-
# # else: moisture okay but not ideal — health stays same
|
| 171 |
-
|
| 172 |
-
# # --- Advance Day ---
|
| 173 |
-
# self._day += 1
|
| 174 |
-
|
| 175 |
-
# # --- Auto Update Crop Stage based on day ---
|
| 176 |
-
# if self._day <= 10:
|
| 177 |
-
# self._crop_stage = CropStage.SEEDLING
|
| 178 |
-
# elif self._day <= 20:
|
| 179 |
-
# self._crop_stage = CropStage.GROWING
|
| 180 |
-
# else:
|
| 181 |
-
# self._crop_stage = CropStage.MATURE
|
| 182 |
-
|
| 183 |
-
# # --- Calculate Reward ---
|
| 184 |
-
# reward = self._calculate_reward(water_added)
|
| 185 |
-
|
| 186 |
-
# # --- Is episode done? ---
|
| 187 |
-
# done = self._day > 30
|
| 188 |
-
|
| 189 |
-
# return FarmObservation(
|
| 190 |
-
# temperature=self._temperature,
|
| 191 |
-
# rainfall=self._rainfall,
|
| 192 |
-
# soil_moisture=self._soil_moisture,
|
| 193 |
-
# crop_health=self._crop_health,
|
| 194 |
-
# day_number=min(self._day, 30),
|
| 195 |
-
# crop_stage=self._crop_stage,
|
| 196 |
-
# done=done,
|
| 197 |
-
# reward=reward,
|
| 198 |
-
# )
|
| 199 |
-
|
| 200 |
-
# def _calculate_reward(self, water_added: float) -> float:
|
| 201 |
-
# """
|
| 202 |
-
# Calculate reward based on soil moisture and water usage.
|
| 203 |
-
# Returns value between -1.0 and 1.0
|
| 204 |
-
# """
|
| 205 |
-
# # Ideal moisture ranges per crop stage
|
| 206 |
-
# ideal_ranges = {
|
| 207 |
-
# CropStage.SEEDLING: (40, 70),
|
| 208 |
-
# CropStage.GROWING: (45, 70),
|
| 209 |
-
# CropStage.MATURE: (35, 60),
|
| 210 |
-
# }
|
| 211 |
-
|
| 212 |
-
# low, high = ideal_ranges[self._crop_stage]
|
| 213 |
-
|
| 214 |
-
# # Perfect moisture range
|
| 215 |
-
# if low <= self._soil_moisture <= high:
|
| 216 |
-
# reward = 1.0
|
| 217 |
-
|
| 218 |
-
# # Acceptable but not ideal
|
| 219 |
-
# elif (low - 10) <= self._soil_moisture <= (high + 10):
|
| 220 |
-
# reward = 0.5
|
| 221 |
-
|
| 222 |
-
# # Too dry
|
| 223 |
-
# elif self._soil_moisture < 20:
|
| 224 |
-
# reward = -1.0
|
| 225 |
-
|
| 226 |
-
# # Too wet
|
| 227 |
-
# elif self._soil_moisture > 90:
|
| 228 |
-
# reward = -0.5
|
| 229 |
-
|
| 230 |
-
# else:
|
| 231 |
-
# reward = 0.0
|
| 232 |
-
|
| 233 |
-
# # Penalize watering on rainy days (water waste)
|
| 234 |
-
# if self._rainfall > 15 and water_added > 0:
|
| 235 |
-
# reward -= 0.3
|
| 236 |
-
|
| 237 |
-
# return round(max(-1.0, min(1.0, reward)), 2)
|
| 238 |
-
|
| 239 |
-
# @property
|
| 240 |
-
# def state(self) -> State:
|
| 241 |
-
# """Return current environment state."""
|
| 242 |
-
# return self._state
|
| 243 |
|
| 244 |
from uuid import uuid4
|
| 245 |
|
|
@@ -247,11 +21,11 @@ from openenv.core.env_server.interfaces import Environment
|
|
| 247 |
from openenv.core.env_server.types import State
|
| 248 |
|
| 249 |
try:
|
| 250 |
-
from .
|
| 251 |
-
from .
|
| 252 |
except ImportError:
|
| 253 |
-
from models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 254 |
-
from weather import WeatherService
|
| 255 |
|
| 256 |
|
| 257 |
class FarmEnvironment(Environment):
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
#This source code is licensed under the BSD-style license found in the
|
| 5 |
+
#LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Smart Farm Irrigation Environment Implementation.
|
| 9 |
+
|
| 10 |
+
A real-world environment where an AI agent manages crop irrigation
|
| 11 |
+
by deciding how much water to give crops each day based on:
|
| 12 |
+
- Weather conditions (temperature, rainfall) from real Weather API
|
| 13 |
+
- Soil moisture (from sensor or auto-calculated)
|
| 14 |
+
- Crop health (user input)
|
| 15 |
+
- Crop stage (auto-managed by code)
|
| 16 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
from uuid import uuid4
|
| 19 |
|
|
|
|
| 21 |
from openenv.core.env_server.types import State
|
| 22 |
|
| 23 |
try:
|
| 24 |
+
from my_env.models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 25 |
+
from my_env.weather import WeatherService
|
| 26 |
except ImportError:
|
| 27 |
+
from my_env.models import FarmAction, FarmObservation, CropStage, CropHealthStatus
|
| 28 |
+
from my_env.weather import WeatherService
|
| 29 |
|
| 30 |
|
| 31 |
class FarmEnvironment(Environment):
|
server/requirements.txt
CHANGED
|
@@ -1,6 +1,4 @@
|
|
| 1 |
-
# openenv[core]>=0.2.0
|
| 2 |
openenv-core[core]>=0.2.1
|
| 3 |
-
# openenv==0.1.13
|
| 4 |
fastapi>=0.115.0
|
| 5 |
uvicorn>=0.24.0
|
| 6 |
requests>=2.32.0
|
|
|
|
|
|
|
| 1 |
openenv-core[core]>=0.2.1
|
|
|
|
| 2 |
fastapi>=0.115.0
|
| 3 |
uvicorn>=0.24.0
|
| 4 |
requests>=2.32.0
|