File size: 1,815 Bytes
52de2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pandas as pd
from fastapi import FastAPI, Request, Form
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from dotenv import load_dotenv
from pathlib import Path

from chatbot import WatershedChatbot

load_dotenv()  

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")

chatbot = WatershedChatbot()

csv_path = Path(__file__).resolve().parent / "summary.csv"

try:
    summary_df = pd.read_csv(csv_path)
except FileNotFoundError:
    dummy_data = pd.DataFrame([
        {
            "district": "Example District",
            "cropping_intensity": 100,
            "soil_loss": 10,
            "check_dams": 5,
            "reforested_area": 200
        }
    ])
    dummy_data.to_csv(csv_path, index=False)
    summary_df = dummy_data
    print(f"[INFO] Created dummy summary.csv at {csv_path}")

summary_df.columns = summary_df.columns.str.lower().str.strip()

@app.get("/", response_class=HTMLResponse)
async def get_home(request: Request):
    districts = ["All"] + sorted(summary_df["district"].unique().tolist())

    summary_data = summary_df.to_dict(orient="records")

    return templates.TemplateResponse("index.html", {
        "request": request,
        "districts": districts,
        "summary_data": summary_data
    })


@app.post("/api/chat")
async def chat_endpoint(query: str = Form(...), district: str = Form(None)):
    try:
        response = chatbot.answer_query(query, district)
        return JSONResponse(content=response)
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})