Vidhiii1711's picture
updated smart-farm.html
e445f2f
Raw History Blame Contribute Delete
9.5 kB
# 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()