File size: 9,495 Bytes
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d5d2ab
 
 
 
fb49915
 
 
9d5d2ab
fb49915
 
 
 
 
9d5d2ab
fb49915
 
 
 
 
 
 
 
 
 
 
60b1d53
fb49915
e445f2f
60b1d53
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e445f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60b1d53
 
 
 
 
 
 
 
 
 
 
 
 
 
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d5d2ab
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d5d2ab
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acbbeb5
 
 
 
 
 
 
 
 
 
 
fb49915
 
acbbeb5
 
 
 
 
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d5d2ab
fb49915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06261f2
fb49915
 
 
 
 
 
60b1d53
 
 
fb49915
 
e77e322
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""
FastAPI application for the Smart Farm Irrigation Environment.

Endpoints:
    - POST /reset:    Reset the environment
    - POST /step:     Execute an action
    - GET /state:     Get current environment state
    - GET /schema:    Get action/observation schemas
    - WS /ws:         WebSocket endpoint for persistent sessions

    # Mandatory Hackathon Endpoints:
    - GET /tasks:     Returns list of all tasks + action schema
    - POST /grader:   Returns score after episode ends
    - GET /baseline:  Runs baseline agent, returns all 3 scores
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "my_env"))

try:
    from openenv.core.env_server.http_server import create_app
except Exception as e:
    raise ImportError(
        "openenv is required for the web interface. Install dependencies with '\n    uv sync\n'"
    ) from e

try:
    from my_env.models import FarmAction, FarmObservation
    from .my_env_environment import FarmEnvironment
except (ModuleNotFoundError, ImportError):
    try:
        from models import FarmAction, FarmObservation
        from server.my_env_environment import FarmEnvironment
    except ModuleNotFoundError:
        import sys
        import os
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from models import FarmAction, FarmObservation
        from server.my_env_environment import FarmEnvironment
from pathlib import Path
from fastapi import Request
from fastapi.responses import JSONResponse,FileResponse,PlainTextResponse,HTMLResponse

from fastapi.staticfiles import StaticFiles

# Create the app with web interface and README integration
app = create_app(
    FarmEnvironment,
    FarmAction,
    FarmObservation,
    env_name="smart-farm-irrigation",
    max_concurrent_envs=1,
)
from fastapi.middleware.cors import CORSMiddleware

# Serve the UI
@app.get("/ui")
async def serve_ui():
    """Serve the Smart Farm UI frontend."""
    try:
        # Look for HTML file in multiple locations
        possible_paths = [
            os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "smart-farm-ui.html"),
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "smart-farm-ui.html"),
            "smart-farm-ui.html",
        ]
        for path in possible_paths:
            if os.path.exists(path):
                with open(path, "r", encoding="utf-8") as f:
                    return HTMLResponse(content=f.read())
                return HTMLResponse(content="<h1>UI file not found</h1>", status_code=404)
    except Exception as e:
      return HTMLResponse(content=f"<h1>Error: {e}</h1>", status_code=500)
@app.get("/openenv.yaml", response_class=PlainTextResponse)
async def serve_openenv_spec():
    """Serve the OpenEnv spec file — required for validation."""
    possible_paths = [
        Path(__file__).parent.parent / "openenv.yaml",  # root (server/../openenv.yaml)
        Path("/app/openenv.yaml"),                        # Docker absolute path
        Path("openenv.yaml"),                             # working directory
    ]
    for p in possible_paths:
        if p.exists():
            return PlainTextResponse(content=p.read_text(), media_type="text/yaml")
    return PlainTextResponse(
        content="openenv.yaml not found", status_code=404
    )
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],   # In production, replace * with your frontend URL
    allow_methods=["*"],
    allow_headers=["*"],
)

# MANDATORY ENDPOINT 1 — /tasks
# Returns list of tasks and action schema
@app.get("/tasks")
async def get_tasks():
    """
    Returns all 3 tasks and the action schema.
    Mandatory endpoint for hackathon submission.
    """
    try:
      from tasks import get_all_tasks
    except ImportError:
        try:
          from my_env.tasks import get_all_tasks
        except ImportError:
           import sys, os
           sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from my_env.tasks import get_all_tasks

    return JSONResponse(content=get_all_tasks())

# MANDATORY ENDPOINT 2 — /grader
# Returns score after episode ends
@app.post("/grader")
async def grade_episode(request: Request):
    """
    Grades a completed episode and returns score.
    
    Expected request body:
    {
        "task_id": 1,
        "episode_history": [
            {
                "day": 1,
                "soil_moisture": 55.0,
                "crop_health": "good",
                "water_action": 2,
                "rainfall": 0.0
            },
            ...
        ]
    }

    Returns score between 0.0 and 1.0
    """
    try:
     from graders import grade_task1, grade_task2, grade_task3
    except ImportError:
      try:
        from my_env.graders import grade_task1, grade_task2, grade_task3
      except ImportError:
        import sys, os
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from my_env.graders import grade_task1, grade_task2, grade_task3

    try:
        body = await request.json()
        task_id = body.get("task_id", 1)
        episode_history = body.get("episode_history", [])

        # Select correct grader
        graders = {
            1: grade_task1,
            2: grade_task2,
            3: grade_task3,
        }

        if task_id not in graders:
            return JSONResponse(
                content={"error": f"Invalid task_id: {task_id}. Must be 1, 2, or 3"},
                status_code=400
            )

        # score = graders[task_id](episode_history)

        # return JSONResponse(content={
        #     "task_id":   task_id,
        #     "score":     score,
        #     "min_score": 0.0,
        #     "max_score": 1.0,
        # })
        raw_score = graders[task_id](episode_history)
        # Clamp strictly between 0 and 1
        score = round(max(0.01, min(0.99, float(raw_score))), 4)

        return JSONResponse(content={
             "task_id":   task_id,
             "score":     score,
             "min_score": 0.01,
             "max_score": 0.99,
})

    except Exception as e:
        return JSONResponse(
            content={"error": str(e)},
            status_code=500
        )

# MANDATORY ENDPOINT 3 — /baseline
# Runs baseline agent, returns all scores
@app.get("/baseline")
async def run_baseline(city: str = "Indore"):
    """
    Runs the baseline rule-based agent through all 3 tasks
    and returns reproducible scores.

    Query params:
        city: City name for weather data (default: Indore)

    Returns scores for all 3 tasks + average score
    """
    try:
     from baseline import main as run_baseline_agent
    except ImportError:
     try:
        from my_env.baseline import main as run_baseline_agent
     except ImportError:
        import sys, os
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from my_env.baseline import main as run_baseline_agent

    try:
        results = run_baseline_agent(city=city)

        # Format results for response
        scores = {}
        for result in results:
            scores[f"task_{result['task_id']}"] = {
                "name":            result["task_name"],
                "score":           result["score"],
                "steps_completed": result["steps_completed"],
            }

        avg = sum(r["score"] for r in results) / len(results)

        return JSONResponse(content={
            "city":          city,
            "agent":         "Simple Rule-Based Agent",
            "scores":        scores,
            "average_score": round(avg, 2),
            "status":        "success"
        })

    except Exception as e:
        return JSONResponse(
            content={"error": str(e)},
            status_code=500
        )

@app.post("/inference-step")
async def inference_step(request: Request):
    """
    Single step LLM decision for UI.
    """
    try:
        from inference import llm_decide
    except ImportError:
        import sys, os
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from inference import llm_decide

    try:
        body = await request.json()
        observation = body.get("observation", {})
        task_id = body.get("task_id", 1)
        day = body.get("day", 1)
        max_days = body.get("max_days", 7)

        action, reason = llm_decide(observation, task_id, day, max_days)

        return JSONResponse(content={
            "action": action,
            "reason": reason
        })

    except Exception as e:
        return JSONResponse(
            content={"error": str(e)},
            status_code=500
        )

def main(host: str = "0.0.0.0", port: int = 7860):
    """
    Entry point for direct execution via uv run or python -m.
    """
    import uvicorn
    uvicorn.run(app, host=host, port=port)

# Mount root directory so openenv.yaml is accessible
_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
app.mount("/static", StaticFiles(directory=_root), name="static")

if __name__ == "__main__":
    main()