Vidhiii1711 commited on
Commit
e7729e5
·
1 Parent(s): f938a7a

feat: Smart Farm Irrigation Environment with real weather API

Browse files
my_env/.gitignore ADDED
Binary file (86 Bytes). View file
 
my_env/README.md ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: My Env Environment Server
3
+ emoji: 📷
4
+ colorFrom: indigo
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 8000
9
+ base_path: /web
10
+ tags:
11
+ - openenv
12
+ ---
13
+
14
+ # My Env Environment
15
+
16
+ A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns.
17
+
18
+ ## Quick Start
19
+
20
+ The simplest way to use the My Env environment is through the `MyEnv` class:
21
+
22
+ ```python
23
+ from my_env import MyAction, MyEnv
24
+
25
+ try:
26
+ # Create environment from Docker image
27
+ my_envenv = MyEnv.from_docker_image("my_env-env:latest")
28
+
29
+ # Reset
30
+ result = my_envenv.reset()
31
+ print(f"Reset: {result.observation.echoed_message}")
32
+
33
+ # Send multiple messages
34
+ messages = ["Hello, World!", "Testing echo", "Final message"]
35
+
36
+ for msg in messages:
37
+ result = my_envenv.step(MyAction(message=msg))
38
+ print(f"Sent: '{msg}'")
39
+ print(f" → Echoed: '{result.observation.echoed_message}'")
40
+ print(f" → Length: {result.observation.message_length}")
41
+ print(f" → Reward: {result.reward}")
42
+
43
+ finally:
44
+ # Always clean up
45
+ my_envenv.close()
46
+ ```
47
+
48
+ That's it! The `MyEnv.from_docker_image()` method handles:
49
+ - Starting the Docker container
50
+ - Waiting for the server to be ready
51
+ - Connecting to the environment
52
+ - Container cleanup when you call `close()`
53
+
54
+ ## Building the Docker Image
55
+
56
+ Before using the environment, you need to build the Docker image:
57
+
58
+ ```bash
59
+ # From project root
60
+ docker build -t my_env-env:latest -f server/Dockerfile .
61
+ ```
62
+
63
+ ## Deploying to Hugging Face Spaces
64
+
65
+ You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:
66
+
67
+ ```bash
68
+ # From the environment directory (where openenv.yaml is located)
69
+ openenv push
70
+
71
+ # Or specify options
72
+ openenv push --namespace my-org --private
73
+ ```
74
+
75
+ The `openenv push` command will:
76
+ 1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)
77
+ 2. Prepare a custom build for Hugging Face Docker space (enables web interface)
78
+ 3. Upload to Hugging Face (ensuring you're logged in)
79
+
80
+ ### Prerequisites
81
+
82
+ - Authenticate with Hugging Face: The command will prompt for login if not already authenticated
83
+
84
+ ### Options
85
+
86
+ - `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory)
87
+ - `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml)
88
+ - `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM)
89
+ - `--private`: Deploy the space as private (default: public)
90
+
91
+ ### Examples
92
+
93
+ ```bash
94
+ # Push to your personal namespace (defaults to username/env-name from openenv.yaml)
95
+ openenv push
96
+
97
+ # Push to a specific repository
98
+ openenv push --repo-id my-org/my-env
99
+
100
+ # Push with a custom base image
101
+ openenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest
102
+
103
+ # Push as a private space
104
+ openenv push --private
105
+
106
+ # Combine options
107
+ openenv push --repo-id my-org/my-env --base-image custom-base:latest --private
108
+ ```
109
+
110
+ After deployment, your space will be available at:
111
+ `https://huggingface.co/spaces/<repo-id>`
112
+
113
+ The deployed space includes:
114
+ - **Web Interface** at `/web` - Interactive UI for exploring the environment
115
+ - **API Documentation** at `/docs` - Full OpenAPI/Swagger interface
116
+ - **Health Check** at `/health` - Container health monitoring
117
+ - **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions
118
+
119
+ ## Environment Details
120
+
121
+ ### Action
122
+ **MyAction**: Contains a single field
123
+ - `message` (str) - The message to echo back
124
+
125
+ ### Observation
126
+ **MyObservation**: Contains the echo response and metadata
127
+ - `echoed_message` (str) - The message echoed back
128
+ - `message_length` (int) - Length of the message
129
+ - `reward` (float) - Reward based on message length (length × 0.1)
130
+ - `done` (bool) - Always False for echo environment
131
+ - `metadata` (dict) - Additional info like step count
132
+
133
+ ### Reward
134
+ The reward is calculated as: `message_length × 0.1`
135
+ - "Hi" → reward: 0.2
136
+ - "Hello, World!" → reward: 1.3
137
+ - Empty message → reward: 0.0
138
+
139
+ ## Advanced Usage
140
+
141
+ ### Connecting to an Existing Server
142
+
143
+ If you already have a My Env environment server running, you can connect directly:
144
+
145
+ ```python
146
+ from my_env import MyEnv
147
+
148
+ # Connect to existing server
149
+ my_envenv = MyEnv(base_url="<ENV_HTTP_URL_HERE>")
150
+
151
+ # Use as normal
152
+ result = my_envenv.reset()
153
+ result = my_envenv.step(MyAction(message="Hello!"))
154
+ ```
155
+
156
+ Note: When connecting to an existing server, `my_envenv.close()` will NOT stop the server.
157
+
158
+ ### Using the Context Manager
159
+
160
+ The client supports context manager usage for automatic connection management:
161
+
162
+ ```python
163
+ from my_env import MyAction, MyEnv
164
+
165
+ # Connect with context manager (auto-connects and closes)
166
+ with MyEnv(base_url="http://localhost:8000") as env:
167
+ result = env.reset()
168
+ print(f"Reset: {result.observation.echoed_message}")
169
+ # Multiple steps with low latency
170
+ for msg in ["Hello", "World", "!"]:
171
+ result = env.step(MyAction(message=msg))
172
+ print(f"Echoed: {result.observation.echoed_message}")
173
+ ```
174
+
175
+ The client uses WebSocket connections for:
176
+ - **Lower latency**: No HTTP connection overhead per request
177
+ - **Persistent session**: Server maintains your environment state
178
+ - **Efficient for episodes**: Better for many sequential steps
179
+
180
+ ### Concurrent WebSocket Sessions
181
+
182
+ The server supports multiple concurrent WebSocket connections. To enable this,
183
+ modify `server/app.py` to use factory mode:
184
+
185
+ ```python
186
+ # In server/app.py - use factory mode for concurrent sessions
187
+ app = create_app(
188
+ MyEnvironment, # Pass class, not instance
189
+ MyAction,
190
+ MyObservation,
191
+ max_concurrent_envs=4, # Allow 4 concurrent sessions
192
+ )
193
+ ```
194
+
195
+ Then multiple clients can connect simultaneously:
196
+
197
+ ```python
198
+ from my_env import MyAction, MyEnv
199
+ from concurrent.futures import ThreadPoolExecutor
200
+
201
+ def run_episode(client_id: int):
202
+ with MyEnv(base_url="http://localhost:8000") as env:
203
+ result = env.reset()
204
+ for i in range(10):
205
+ result = env.step(MyAction(message=f"Client {client_id}, step {i}"))
206
+ return client_id, result.observation.message_length
207
+
208
+ # Run 4 episodes concurrently
209
+ with ThreadPoolExecutor(max_workers=4) as executor:
210
+ results = list(executor.map(run_episode, range(4)))
211
+ ```
212
+
213
+ ## Development & Testing
214
+
215
+ ### Direct Environment Testing
216
+
217
+ Test the environment logic directly without starting the HTTP server:
218
+
219
+ ```bash
220
+ # From the server directory
221
+ python3 server/my_env_environment.py
222
+ ```
223
+
224
+ This verifies that:
225
+ - Environment resets correctly
226
+ - Step executes actions properly
227
+ - State tracking works
228
+ - Rewards are calculated correctly
229
+
230
+ ### Running Locally
231
+
232
+ Run the server locally for development:
233
+
234
+ ```bash
235
+ uvicorn server.app:app --reload
236
+ ```
237
+
238
+ ## Project Structure
239
+
240
+ ```
241
+ my_env/
242
+ ├── .dockerignore # Docker build exclusions
243
+ ├── __init__.py # Module exports
244
+ ├── README.md # This file
245
+ ├── openenv.yaml # OpenEnv manifest
246
+ ├── pyproject.toml # Project metadata and dependencies
247
+ ├── uv.lock # Locked dependencies (generated)
248
+ ├── client.py # MyEnv client
249
+ ├── models.py # Action and Observation models
250
+ └── server/
251
+ ├── __init__.py # Server module exports
252
+ ├── my_env_environment.py # Core environment logic
253
+ ├── app.py # FastAPI application (HTTP + WebSocket endpoints)
254
+ └── Dockerfile # Container image definition
255
+ ```
my_env/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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."""
8
+
9
+ from .client import FarmEnv
10
+ from .models import FarmAction, FarmObservation
11
+
12
+ __all__ = [
13
+ "FarmAction",
14
+ "FarmObservation",
15
+ "FarmEnv",
16
+ ]
my_env/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (444 Bytes). View file
 
my_env/__pycache__/client.cpython-313.pyc ADDED
Binary file (3.82 kB). View file
 
my_env/__pycache__/models.cpython-313.pyc ADDED
Binary file (1.45 kB). View file
 
my_env/baseline.py ADDED
File without changes
my_env/client.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Client."""
8
+
9
+ from typing import Dict
10
+
11
+ from openenv.core import EnvClient
12
+ from openenv.core.client_types import StepResult
13
+ from openenv.core.env_server.types import State
14
+
15
+ from .models import FarmAction, FarmObservation
16
+
17
+ class FarmEnv(
18
+ EnvClient[FarmAction, FarmObservation, State]
19
+ ):
20
+ """
21
+ Client for the Smart Farm Irrigation Environment.
22
+
23
+ This client maintains a persistent WebSocket connection to the
24
+ environment server, enabling efficient multi-step interactions.
25
+ Each client instance has its own dedicated environment session.
26
+
27
+ Example:
28
+ >>> with FarmEnv(base_url="http://localhost:8000") as client:
29
+ ... result = client.reset()
30
+ ... result = client.step(FarmAction(water_amount="medium"))
31
+ ... print(result.observation.crop_health)
32
+ """
33
+
34
+ def _step_payload(self, action: FarmAction) -> Dict:
35
+ """
36
+ Convert FarmAction to JSON payload for step message.
37
+
38
+ Args:
39
+ action: FarmAction instance
40
+
41
+ Returns:
42
+ Dictionary representation suitable for JSON encoding
43
+ """
44
+ return {
45
+ "water_amount": action.water_amount.value,
46
+ }
47
+
48
+ def _parse_result(self, payload: Dict) -> StepResult[FarmObservation]:
49
+ """
50
+ Parse server response into StepResult[FarmObservation].
51
+
52
+ Args:
53
+ payload: JSON response data from server
54
+
55
+ Returns:
56
+ StepResult with FarmObservation
57
+ """
58
+ obs_data = payload.get("observation", {})
59
+ observation = FarmObservation(
60
+ temperature=obs_data.get("temperature", 30.0),
61
+ rainfall=obs_data.get("rainfall", 0.0),
62
+ soil_moisture=obs_data.get("soil_moisture", None),
63
+ crop_health=obs_data.get("crop_health", "fair"),
64
+ day_number=obs_data.get("day_number", 1),
65
+ crop_stage=obs_data.get("crop_stage", "seedling"),
66
+ done=payload.get("done", False),
67
+ reward=payload.get("reward"),
68
+ metadata=obs_data.get("metadata", {}),
69
+ )
70
+
71
+ return StepResult(
72
+ observation=observation,
73
+ reward=payload.get("reward"),
74
+ done=payload.get("done", False),
75
+ )
76
+
77
+ def _parse_state(self, payload: Dict) -> State:
78
+ """
79
+ Parse server response into State object.
80
+
81
+ Args:
82
+ payload: JSON response from state request
83
+
84
+ Returns:
85
+ State object with episode_id and step_count
86
+ """
87
+ return State(
88
+ episode_id=payload.get("episode_id"),
89
+ step_count=payload.get("step_count", 0),
90
+ )
my_env/models.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Data models for the Smart Farm Irrigation Environment.
9
+
10
+ This environment simulates a real-world crop irrigation management task
11
+ where an AI agent decides how much to water crops based on:
12
+ - Weather conditions (temperature, rainfall) from Weather API
13
+ - Soil moisture (from sensor if available, else calculated)
14
+ - Crop health (selected by user)
15
+ - Crop stage and day number (auto-managed by code)
16
+ """
17
+
18
+ from enum import Enum
19
+ from typing import Optional
20
+ from openenv.core.env_server.types import Action, Observation
21
+ from pydantic import Field
22
+
23
+ class CropHealthStatus(str, Enum):
24
+ """
25
+ User selects current crop health.
26
+ Like a dropdown — only these 4 options allowed.
27
+ """
28
+ POOR="poor"
29
+ FAIR="fair"
30
+ GOOD="good"
31
+ EXCELLENT="excellent"
32
+
33
+ class WaterAmount(str, Enum):
34
+ """
35
+ AI selects how much to water the crop.
36
+ This is the ACTION the AI takes every day.
37
+ """
38
+ NONE="none"
39
+ LOW="low"
40
+ MEDIUM="medium"
41
+ HIGH="high"
42
+
43
+ class CropStage(str, Enum):
44
+ """
45
+ Crop growth stage — automatically set by code based on day number.
46
+ User never touches this. Code manages it.
47
+ Day 1-10 → Seedling
48
+ Day 11-20 → Growing
49
+ Day 21-30 → Mature
50
+ """
51
+ SEEDLING = "seedling"
52
+ GROWING="growing"
53
+ MATURE="mature"
54
+
55
+ class FarmObservation(Observation):
56
+ """
57
+ Everything the AI can observe about the farm at any given moment.
58
+
59
+ Sources:
60
+ - temperature, rainfall → fetched from Weather API
61
+ - soil_moisture → from sensor (optional) or calculated
62
+ - crop_health → selected by user (dropdown)
63
+ - day_number, crop_stage → auto-managed by code
64
+ """
65
+
66
+ #FROM WEATHER API
67
+ temperature: float = Field(
68
+ ...,
69
+ description="Current temperature in Celsius (from Weather API)",
70
+ ge=0.0, #min
71
+ le=60.0 #max
72
+ )
73
+
74
+ rainfall: float = Field(
75
+ ...,
76
+ description="Rainfall today in mm (from Weather API)",
77
+ ge=0.0, #min
78
+ le=500.0 #max
79
+ )
80
+
81
+ #FROM SENSOR OR CALCULATED
82
+ soil_moisture: Optional[float] = Field(
83
+ default=None,
84
+ description=(
85
+ "Soil moisture percentage (0-100). "
86
+ "Provide this if you have a sensor. "
87
+ "If None, code will calculate it automatically "
88
+ "based on rainfall and temperature."
89
+ ),
90
+ ge=0.0,
91
+ le=100.0
92
+ )
93
+
94
+ #USER SELECTS
95
+ crop_health: CropHealthStatus = Field(
96
+ ...,
97
+ description="Current crop health selected by user (poor/fair/good/excellent)"
98
+ )
99
+
100
+ #AUTO MANAGED BY CODE
101
+ day_number: int = Field(
102
+ default=1,
103
+ description="Current day of simulation (1-30). Auto-incremented by code.",
104
+ ge=1,
105
+ le=30
106
+ )
107
+
108
+ crop_stage: CropStage = Field(
109
+ default=CropStage.SEEDLING,
110
+ description="Current crop growth stage. Auto-set by code based on day_number."
111
+ )
112
+
113
+ class FarmAction(Action):
114
+ """
115
+ The only decision the AI makes every day:
116
+ How much water should I give the crop today?
117
+ """
118
+
119
+ water_amount: WaterAmount = Field(
120
+ ...,
121
+ description=(
122
+ "How much to water the crop today. "
123
+ "none=0mm, low=10mm, medium=25mm, high=50mm"
124
+ )
125
+ )
126
+
127
+ class FarmReward:
128
+ """
129
+ Score given to AI after each action.
130
+ Tells the AI how well it did.
131
+ """
132
+
133
+ value: float = Field(
134
+ ...,
135
+ description="Reward score between 0.0 (worst) and 1.0 (best)",
136
+ ge=-1.0, # can go negative for very bad actions
137
+ le=1.0
138
+ )
139
+
140
+ reason: str = Field(
141
+ ...,
142
+ description="Human-readable explanation of why this score was given"
143
+ )
my_env/openenv.yaml ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: smart-farm-irrigation
3
+ type: space
4
+ runtime: fastapi
5
+ app: server.app:app
6
+ port: 8000
7
+
8
+ metadata:
9
+ title: Smart Farm Irrigation Assistant
10
+ description: >
11
+ An AI environment that simulates real-world crop irrigation management.
12
+ The AI agent decides how much to water crops daily based on weather
13
+ conditions, soil moisture, and crop health to maximize crop yield
14
+ while minimizing water waste.
15
+ author: Vidhi Singh
16
+ version: 1.0.0
17
+ tags:
18
+ - agriculture
19
+ - irrigation
20
+ - real-world
21
+ - water-conservation
22
+ - india
23
+
24
+ tasks:
25
+ - name: easy_irrigation
26
+ description: >
27
+ Keep soil moisture in healthy range for 7 days.
28
+ Fixed temperature, no rainfall. Beginner level.
29
+ difficulty: easy
30
+ max_steps: 7
31
+ scoring: 0.0-1.0
32
+
33
+ - name: medium_irrigation
34
+ description: >
35
+ Manage irrigation across 14 days with changing
36
+ temperatures and random rainfall events.
37
+ AI must avoid watering on rainy days.
38
+ difficulty: medium
39
+ max_steps: 14
40
+ scoring: 0.0-1.0
41
+
42
+ - name: hard_irrigation
43
+ description: >
44
+ Full 30-day crop season management across 3 crop
45
+ stages (seedling, growing, mature). Each stage needs
46
+ different moisture levels. Maximize final crop yield.
47
+ difficulty: hard
48
+ max_steps: 30
49
+ scoring: 0.0-1.0
50
+
51
+ observation_space:
52
+ temperature:
53
+ type: float
54
+ range: 0.0-60.0
55
+ unit: celsius
56
+ source: weather_api
57
+ rainfall:
58
+ type: float
59
+ range: 0.0-500.0
60
+ unit: mm
61
+ source: weather_api
62
+ soil_moisture:
63
+ type: float
64
+ range: 0.0-100.0
65
+ unit: percentage
66
+ source: sensor_or_calculated
67
+ optional: true
68
+ crop_health:
69
+ type: enum
70
+ options: [poor, fair, good, excellent]
71
+ source: user_input
72
+ day_number:
73
+ type: integer
74
+ range: 1-30
75
+ source: auto
76
+ crop_stage:
77
+ type: enum
78
+ options: [seedling, growing, mature]
79
+ source: auto
80
+
81
+ action_space:
82
+ water_amount:
83
+ type: enum
84
+ options:
85
+ none: 0mm of water
86
+ low: 10mm of water
87
+ medium: 25mm of water
88
+ high: 50mm of water
89
+
90
+ reward:
91
+ type: float
92
+ range: -1.0 to 1.0
93
+ signals:
94
+ - moisture_in_ideal_range
95
+ - water_conservation_bonus
96
+ - rain_day_penalty
97
+ - crop_stage_compliance
98
+ - final_yield_score
99
+
my_env/pyproject.toml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [build-system]
8
+ requires = ["setuptools>=45", "wheel"]
9
+ build-backend = "setuptools.build_meta"
10
+
11
+ [project]
12
+ name = "openenv-my_env"
13
+ version = "0.1.0"
14
+ description = "My Env environment for OpenEnv"
15
+ requires-python = ">=3.10"
16
+ dependencies = [
17
+ # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
18
+ # install from github
19
+ # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
20
+ "openenv-core[core]>=0.2.1",
21
+ # Environment-specific dependencies
22
+ # Add all dependencies needed for your environment here
23
+ # Examples:
24
+ # "numpy>=1.19.0",
25
+ # "torch>=2.0.0",
26
+ # "gymnasium>=0.29.0",
27
+ # "openspiel>=1.0.0",
28
+ # "smolagents>=1.22.0,<2",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pytest>=8.0.0",
34
+ "pytest-cov>=4.0.0",
35
+ ]
36
+
37
+ [project.scripts]
38
+ # Server entry point - enables running via: uv run --project . server
39
+ # or: python -m my_env.server.app
40
+ server = "my_env.server.app:main"
41
+
42
+ [tool.setuptools]
43
+ include-package-data = true
44
+ packages = ["my_env", "my_env.server"]
45
+ package-dir = { "my_env" = ".", "my_env.server" = "server" }
my_env/server/Dockerfile ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Multi-stage build using openenv-base
8
+ # This Dockerfile is flexible and works for both:
9
+ # - In-repo environments (with local OpenEnv sources)
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/env:$PYTHONPATH"
73
+
74
+ # Health check
75
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
76
+ CMD curl -f http://localhost:8000/health || exit 1
77
+
78
+ # Run the FastAPI server
79
+ # The module path is constructed to work with the /app/env structure
80
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
my_env/server/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
Binary file (386 Bytes). View file
 
my_env/server/__pycache__/app.cpython-313.pyc ADDED
Binary file (2.78 kB). View file
 
my_env/server/__pycache__/my_env_environment.cpython-313.pyc ADDED
Binary file (3.81 kB). View file
 
my_env/server/app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ This module creates an HTTP server that exposes the FarmEnvironment
11
+ over HTTP and WebSocket endpoints, compatible with EnvClient.
12
+
13
+ Endpoints:
14
+ - POST /reset: Reset the environment
15
+ - POST /step: Execute an action
16
+ - GET /state: Get current environment state
17
+ - GET /schema: Get action/observation schemas
18
+ - WS /ws: WebSocket endpoint for persistent sessions
19
+
20
+ Usage:
21
+ # Development (with auto-reload):
22
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
23
+
24
+ # Production:
25
+ uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
26
+
27
+ # Or run directly:
28
+ python -m server.app
29
+ """
30
+
31
+ try:
32
+ from openenv.core.env_server.http_server import create_app
33
+ except Exception as e: # pragma: no cover
34
+ raise ImportError(
35
+ "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
+ ) from e
37
+
38
+ try:
39
+ from ..models import FarmAction, FarmObservation
40
+ from .my_env_environment import FarmEnvironment
41
+ except ModuleNotFoundError:
42
+ from models import FarmAction, FarmObservation
43
+ from server.my_env_environment import FarmEnvironment
44
+
45
+ # Create the app with web interface and README integration
46
+ app = create_app(
47
+ FarmEnvironment,
48
+ FarmAction,
49
+ FarmObservation,
50
+ env_name="smart-farm-irrigation",
51
+ max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions
52
+ )
53
+
54
+
55
+ def main(host: str = "0.0.0.0", port: int = 8000):
56
+ """
57
+ Entry point for direct execution via uv run or python -m.
58
+
59
+ This function enables running the server without Docker:
60
+ uv run --project . server
61
+ uv run --project . server --port 8001
62
+ python -m my_env.server.app
63
+
64
+ Args:
65
+ host: Host address to bind to (default: "0.0.0.0")
66
+ port: Port number to listen on (default: 8000)
67
+
68
+ For production deployments, consider using uvicorn directly with
69
+ multiple workers:
70
+ uvicorn my_env.server.app:app --workers 4
71
+ """
72
+ import uvicorn
73
+
74
+ uvicorn.run(app, host=host, port=port)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ import argparse
79
+
80
+ parser = argparse.ArgumentParser()
81
+ parser.add_argument("--port", type=int, default=8000)
82
+ args = parser.parse_args()
83
+ main(port=args.port)
my_env/server/my_env_environment.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=30.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
+ # --- Fetch Fresh Weather for Today ---
136
+ weather = self._weather_service.get_weather(self._city)
137
+ self._temperature = weather["temperature"]
138
+ self._rainfall = weather["rainfall"]
139
+
140
+ # --- Update Soil Moisture ---
141
+ if self._sensor_moisture is not None:
142
+ # sensor user — just add water and subtract evaporation
143
+ evaporation = (self._temperature / 100) * 10
144
+ self._soil_moisture = self._soil_moisture + water_added - evaporation
145
+ else:
146
+ # no sensor — use weather calculator
147
+ self._soil_moisture = self._weather_service.calculate_soil_moisture(
148
+ current_moisture=self._soil_moisture + water_added,
149
+ temperature=self._temperature,
150
+ rainfall=self._rainfall
151
+ )
152
+
153
+ # Keep moisture in valid range 0-100
154
+ self._soil_moisture = max(0.0, min(100.0, self._soil_moisture))
155
+
156
+ # --- Advance Day ---
157
+ self._day += 1
158
+
159
+ # --- Auto Update Crop Stage based on day ---
160
+ if self._day <= 10:
161
+ self._crop_stage = CropStage.SEEDLING
162
+ elif self._day <= 20:
163
+ self._crop_stage = CropStage.GROWING
164
+ else:
165
+ self._crop_stage = CropStage.MATURE
166
+
167
+ # --- Calculate Reward ---
168
+ reward = self._calculate_reward(water_added)
169
+
170
+ # --- Is episode done? ---
171
+ done = self._day > 30
172
+
173
+ return FarmObservation(
174
+ temperature=self._temperature,
175
+ rainfall=self._rainfall,
176
+ soil_moisture=self._soil_moisture,
177
+ crop_health=self._crop_health,
178
+ day_number=min(self._day, 30),
179
+ crop_stage=self._crop_stage,
180
+ done=done,
181
+ reward=reward,
182
+ )
183
+
184
+ def _calculate_reward(self, water_added: float) -> float:
185
+ """
186
+ Calculate reward based on soil moisture and water usage.
187
+ Returns value between -1.0 and 1.0
188
+ """
189
+ # Ideal moisture ranges per crop stage
190
+ ideal_ranges = {
191
+ CropStage.SEEDLING: (50, 60),
192
+ CropStage.GROWING: (60, 75),
193
+ CropStage.MATURE: (40, 55),
194
+ }
195
+
196
+ low, high = ideal_ranges[self._crop_stage]
197
+
198
+ # Perfect moisture range
199
+ if low <= self._soil_moisture <= high:
200
+ reward = 1.0
201
+
202
+ # Acceptable but not ideal
203
+ elif (low - 10) <= self._soil_moisture <= (high + 10):
204
+ reward = 0.5
205
+
206
+ # Too dry
207
+ elif self._soil_moisture < 20:
208
+ reward = -1.0
209
+
210
+ # Too wet
211
+ elif self._soil_moisture > 90:
212
+ reward = -0.5
213
+
214
+ else:
215
+ reward = 0.0
216
+
217
+ # Penalize watering on rainy days (water waste)
218
+ if self._rainfall > 15 and water_added > 0:
219
+ reward -= 0.3
220
+
221
+ return round(max(-1.0, min(1.0, reward)), 2)
222
+
223
+ @property
224
+ def state(self) -> State:
225
+ """Return current environment state."""
226
+ return self._state
my_env/server/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openenv[core]>=0.2.0
2
+ fastapi>=0.115.0
3
+ uvicorn>=0.24.0
4
+ requests>=2.32.0
5
+
6
+
my_env/tasks.py ADDED
File without changes
my_env/uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
my_env/weather.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Weather API Integration for Smart Farm Irrigation Environment.
9
+
10
+ Fetches real-world weather data (temperature, rainfall) for any city
11
+ using two free APIs:
12
+ - Open-Meteo API: Fetches temperature and rainfall (no API key needed!)
13
+ - Nominatim API: Converts city name to latitude/longitude (no API key needed!)
14
+
15
+ Usage:
16
+ weather = WeatherService()
17
+ data = weather.get_weather("Indore")
18
+ print(data["temperature"]) # 38.5
19
+ print(data["rainfall"]) # 0.0
20
+ """
21
+
22
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
23
+ # All rights reserved.
24
+ #
25
+ # This source code is licensed under the BSD-style license found in the
26
+ # LICENSE file in the root directory of this source tree.
27
+
28
+ """
29
+ Weather API Integration for Smart Farm Irrigation Environment.
30
+
31
+ Fetches real-world weather data (temperature, rainfall) for any city
32
+ using two free APIs:
33
+ - Open-Meteo API: Fetches temperature and rainfall (no API key needed!)
34
+ - Nominatim API: Converts city name to latitude/longitude (no API key needed!)
35
+
36
+ Usage:
37
+ weather = WeatherService()
38
+ data = weather.get_weather("Indore")
39
+ print(data["temperature"]) # 38.5
40
+ print(data["rainfall"]) # 0.0
41
+ """
42
+
43
+ import requests
44
+
45
+ class WeatherService:
46
+ """
47
+ Fetches real-time weather data for any city in the world.
48
+ Uses completely free APIs — no API key needed!
49
+ """
50
+
51
+ # API URLs
52
+ GEOCODING_URL = "https://nominatim.openstreetmap.org/search"
53
+ WEATHER_URL = "https://api.open-meteo.com/v1/forecast"
54
+
55
+ def __init__(self):
56
+ """Initialize with default fallback weather values."""
57
+ self._default_temperature = 30.0
58
+ self._default_rainfall = 0.0
59
+
60
+ def get_coordinates(self, city_name: str) -> tuple:
61
+ """
62
+ Convert a city name to latitude and longitude.
63
+
64
+ Example:
65
+ "Indore" → (22.7196, 75.8577)
66
+ "Mumbai" → (19.0760, 72.8777)
67
+
68
+ Args:
69
+ city_name: Name of any city in the world
70
+
71
+ Returns:
72
+ Tuple of (latitude, longitude)
73
+ Returns default India coords if city not found
74
+ """
75
+ try:
76
+ response = requests.get(
77
+ self.GEOCODING_URL,
78
+ params={
79
+ "q": city_name,
80
+ "format": "json",
81
+ "limit": 1,
82
+ },
83
+ headers={
84
+ "User-Agent": "SmartFarmIrrigationEnv/1.0"
85
+ },
86
+ timeout=5
87
+ )
88
+
89
+ data = response.json()
90
+
91
+ if data:
92
+ lat = float(data[0]["lat"])
93
+ lon = float(data[0]["lon"])
94
+ return (lat, lon)
95
+ else:
96
+ print(f"City '{city_name}' not found. Using Indore as default.")
97
+ return (22.7196, 75.8577)
98
+
99
+ except Exception as e:
100
+ print(f"Geocoding error: {e}. Using default location.")
101
+ return (22.7196, 75.8577)
102
+
103
+ def get_weather(self, city_name: str) -> dict:
104
+ """
105
+ Fetch today's weather data for any city.
106
+
107
+ Args:
108
+ city_name: Name of any city
109
+
110
+ Returns:
111
+ Dictionary with temperature and rainfall
112
+ """
113
+ # Step 1: Get coordinates for the city
114
+ lat, lon = self.get_coordinates(city_name)
115
+
116
+ try:
117
+ # Step 2: Fetch weather from Open-Meteo
118
+ response = requests.get(
119
+ self.WEATHER_URL,
120
+ params={
121
+ "latitude": lat,
122
+ "longitude": lon,
123
+ "current": [
124
+ "temperature_2m",
125
+ "precipitation"
126
+ ],
127
+ "timezone": "auto",
128
+ },
129
+ timeout=5
130
+ )
131
+
132
+ data = response.json()
133
+
134
+ # Step 3: Extract the values we need
135
+ current = data.get("current", {})
136
+ temperature = current.get("temperature_2m", self._default_temperature)
137
+ rainfall = current.get("precipitation", self._default_rainfall)
138
+
139
+ return {
140
+ "temperature": round(float(temperature), 1),
141
+ "rainfall": round(float(rainfall), 1),
142
+ "city": city_name,
143
+ "latitude": lat,
144
+ "longitude": lon,
145
+ }
146
+
147
+ except Exception as e:
148
+ print(f"Weather API error: {e}. Using default values.")
149
+ return {
150
+ "temperature": self._default_temperature,
151
+ "rainfall": self._default_rainfall,
152
+ "city": city_name,
153
+ "latitude": lat,
154
+ "longitude": lon,
155
+ }
156
+
157
+ def calculate_soil_moisture(
158
+ self,
159
+ current_moisture: float,
160
+ temperature: float,
161
+ rainfall: float
162
+ ) -> float:
163
+ """
164
+ Auto-calculate soil moisture when no sensor is available.
165
+
166
+ Args:
167
+ current_moisture: Current soil moisture percentage
168
+ temperature: Current temperature in Celsius
169
+ rainfall: Today's rainfall in mm
170
+
171
+ Returns:
172
+ Updated soil moisture percentage (0.0 to 100.0)
173
+ """
174
+ # Evaporation increases with temperature
175
+ if temperature >= 40:
176
+ evaporation = 8.0
177
+ elif temperature >= 30:
178
+ evaporation = 5.0
179
+ elif temperature >= 20:
180
+ evaporation = 3.0
181
+ else:
182
+ evaporation = 1.0
183
+
184
+ # Rainfall adds moisture to soil
185
+ moisture_from_rain = rainfall * 0.4
186
+
187
+ # Calculate new moisture
188
+ new_moisture = current_moisture - evaporation + moisture_from_rain
189
+
190
+ # Keep in valid range 0-100
191
+ new_moisture = max(0.0, min(100.0, new_moisture))
192
+
193
+ return round(new_moisture, 1)
194
+
195
+ # This runs ONLY when you directly run this file
196
+ if __name__ == "__main__":
197
+ print("Testing Weather Service...")
198
+ print("-" * 40)
199
+
200
+ service = WeatherService()
201
+
202
+ for city in ["Indore", "Mumbai", "Delhi"]:
203
+ data = service.get_weather(city)
204
+ print(f"City: {data['city']}")
205
+ print(f"Temperature: {data['temperature']}°C")
206
+ print(f"Rainfall: {data['rainfall']}mm")
207
+ print("-" * 40)