forked from aisha-sk/COE-Database-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_routes.py
More file actions
61 lines (50 loc) · 1.99 KB
/
query_routes.py
File metadata and controls
61 lines (50 loc) · 1.99 KB
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
from pathlib import Path
from typing import Optional
import pandas as pd
from fastapi import APIRouter, HTTPException, Query
DATA_PATH = Path(__file__).resolve().parent / "data" / "sample_studies.csv"
router = APIRouter(prefix="/query", tags=["traffic-studies"])
@router.get("/studies")
def get_studies(
start_year: int = Query(..., description="First year to include"),
end_year: int = Query(..., description="Last year to include"),
direction: Optional[str] = Query(
None,
description="Direction filter (e.g., Northbound). Use 'All' or omit to include every direction.",
),
):
if start_year > end_year:
raise HTTPException(status_code=400, detail="start_year must be less than or equal to end_year")
try:
df = pd.read_csv(DATA_PATH)
except FileNotFoundError as exc:
raise HTTPException(status_code=500, detail=f"Dataset not found at {DATA_PATH}") from exc
except pd.errors.ParserError as exc:
raise HTTPException(status_code=500, detail="Failed to parse sample_studies.csv") from exc
filtered = df[(df["year"] >= start_year) & (df["year"] <= end_year)]
if direction and direction.lower() != "all":
filtered = filtered[filtered["direction"].str.lower() == direction.lower()]
features = []
for _, row in filtered.iterrows():
try:
lat = float(row["lat"])
lon = float(row["lon"])
except (TypeError, ValueError):
# Skip rows that do not have valid coordinates
continue
feature = {
"type": "Feature",
"properties": {
"id": row["id"],
"year": int(row["year"]),
"direction": row["direction"],
"lat": lat,
"lon": lon,
},
"geometry": {
"type": "Point",
"coordinates": [lon, lat],
},
}
features.append(feature)
return {"type": "FeatureCollection", "features": features}