diff --git a/backend/main.py b/backend/main.py index 6697f0ee..d303056d 100644 --- a/backend/main.py +++ b/backend/main.py @@ -11,6 +11,7 @@ import json import os import io +import sys # Add the project root to sys.path so we can import 'backend' modules sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) @@ -226,37 +227,23 @@ async def create_issue( image: UploadFile = File(...), db: Session = Depends(get_db) ): - try: - # Save the uploaded image - os.makedirs("data/uploads", exist_ok=True) - filename = f"{uuid.uuid4()}_{image.filename}" - file_location = f"data/uploads/{filename}" + # Save the uploaded image + os.makedirs("data/uploads", exist_ok=True) + filename = f"{uuid.uuid4()}_{image.filename}" + file_location = f"data/uploads/{filename}" + + # Offload blocking file I/O to a thread + def save_file(): + with open(file_location, "wb") as buffer: + shutil.copyfileobj(image.file, buffer) - # Offload blocking file I/O to a thread - def save_file(): - with open(image_path, "wb") as buffer: - shutil.copyfileobj(image.file, buffer) + await asyncio.to_thread(save_file) - await asyncio.to_thread(save_file) + # Generate Action Plan (AI) + action_plan = await generate_action_plan(description, category, file_location) # Offload blocking DB operations to a thread def save_to_db(): - new_issue = Issue( - description=description, - category=category, - image_path=image_path, - source="web" - ) - db.add(new_issue) - db.commit() - db.refresh(new_issue) - return new_issue - - new_issue = await asyncio.to_thread(save_to_db) - - # Generate Action Plan (AI) - action_plan = await generate_action_plan(description, category, file_location) - db_issue = Issue( description=description, category=category, @@ -267,6 +254,9 @@ def save_to_db(): db.add(db_issue) db.commit() db.refresh(db_issue) + return db_issue + + new_issue = await asyncio.to_thread(save_to_db) return { "id": new_issue.id, diff --git a/backend/spatial_utils.py b/backend/spatial_utils.py index 8af329a3..557afe91 100644 --- a/backend/spatial_utils.py +++ b/backend/spatial_utils.py @@ -76,10 +76,17 @@ def find_nearby_issues( """ nearby_issues = [] + # Pre-filter using bounding box with 5% epsilon to optimize expensive haversine calculations + min_lat, max_lat, min_lon, max_lon = get_bounding_box(target_lat, target_lon, radius_meters * 1.05) + for issue in issues: if issue.latitude is None or issue.longitude is None: continue + # Fast bounding box pre-filter check + if not (min_lat <= issue.latitude <= max_lat and min_lon <= issue.longitude <= max_lon): + continue + distance = haversine_distance( target_lat, target_lon, issue.latitude, issue.longitude