-
Notifications
You must be signed in to change notification settings - Fork 35
Optimize Backend Latency and Fix Logic #344
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
7f657f9
6f41563
c697473
3168650
1f33f57
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,35 +1,53 @@ | ||
| import os | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| # Add project root to sys.path to ensure 'backend.*' imports work | ||
| # This handles cases where PYTHONPATH is set to 'backend' (e.g. on Render) | ||
| current_file = Path(__file__).resolve() | ||
| backend_dir = current_file.parent | ||
| repo_root = backend_dir.parent | ||
|
|
||
| if str(repo_root) not in sys.path: | ||
| sys.path.insert(0, str(repo_root)) | ||
|
|
||
| from fastapi import FastAPI | ||
| from fastapi import FastAPI, Form, UploadFile, File, Depends, BackgroundTasks, Request, Query | ||
| from fastapi.middleware.cors import CORSMiddleware | ||
| from fastapi.middleware.gzip import GZipMiddleware | ||
| from fastapi.concurrency import run_in_threadpool | ||
| from contextlib import asynccontextmanager | ||
| from functools import lru_cache | ||
| from typing import List | ||
| import os | ||
| import sys | ||
| from pathlib import Path | ||
| import httpx | ||
| import logging | ||
| import asyncio | ||
|
|
||
| from backend.database import Base, engine | ||
| from backend.ai_factory import create_all_ai_services | ||
| from backend.ai_interfaces import initialize_ai_services | ||
| from backend.bot import start_bot_thread, stop_bot_thread | ||
| from backend.init_db import migrate_db | ||
| from backend.maharashtra_locator import load_maharashtra_pincode_data, load_maharashtra_mla_data | ||
| from backend.exceptions import EXCEPTION_HANDLERS | ||
| from backend.routers import issues, detection, grievances, utility | ||
| import time | ||
| import magic | ||
| import httpx | ||
| from backend.grievance_classifier import get_grievance_classifier | ||
| from backend.schemas import GrievanceRequest, ChatRequest, IssueResponse | ||
| from backend.grievance_service import GrievanceService | ||
| from backend.database import Base, engine, get_db, SessionLocal | ||
| from sqlalchemy.orm import Session | ||
| import backend.dependencies | ||
| from backend.models import Issue | ||
| from backend.ai_factory import create_all_ai_services | ||
| from backend.ai_interfaces import initialize_ai_services, get_ai_services | ||
| from backend.ai_service import chat_with_civic_assistant, generate_action_plan | ||
| from backend.bot import run_bot, start_bot_thread, stop_bot_thread | ||
| from backend.exceptions import EXCEPTION_HANDLERS | ||
| from backend.init_db import migrate_db | ||
| from backend.maharashtra_locator import load_maharashtra_pincode_data, load_maharashtra_mla_data, find_constituency_by_pincode, find_mla_by_constituency | ||
| from backend.cache import recent_issues_cache | ||
| from backend.pothole_detection import detect_potholes | ||
| from backend.garbage_detection import detect_garbage | ||
| from backend.local_ml_service import detect_infrastructure_local, detect_flooding_local, detect_vandalism_local | ||
| from backend.unified_detection_service import get_detection_status | ||
| from backend.hf_api_service import ( | ||
| detect_illegal_parking_clip, | ||
| detect_street_light_clip, | ||
| detect_fire_clip, | ||
| detect_stray_animal_clip, | ||
| detect_blocked_road_clip, | ||
| detect_tree_hazard_clip, | ||
| detect_pest_clip, | ||
| detect_severity_clip, | ||
| detect_smart_scan_clip, | ||
| generate_image_caption | ||
| ) | ||
|
|
||
| def validate_image_for_processing(image): | ||
| if not image: | ||
| pass | ||
|
Comment on lines
+48
to
+50
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Broken validation: function does nothing instead of raising an error. This If code in 🐛 Option 1: Remove placeholder and import from utils-def validate_image_for_processing(image):
- if not image:
- pass
+from backend.utils import validate_image_for_processing🐛 Option 2: Fix to match utils implementation+from fastapi import HTTPException
+
def validate_image_for_processing(image):
+ """Validate image before processing."""
if not image:
- pass
+ raise HTTPException(status_code=400, detail="No image provided")🤖 Prompt for AI Agents |
||
|
|
||
| # Configure structured logging | ||
| logging.basicConfig( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -82,7 +82,7 @@ class Grievance(Base): | |
| created_at = Column(DateTime, default=lambda: datetime.datetime.now(datetime.timezone.utc), index=True) | ||
| updated_at = Column(DateTime, default=lambda: datetime.datetime.now(datetime.timezone.utc), onupdate=lambda: datetime.datetime.now(datetime.timezone.utc)) | ||
| resolved_at = Column(DateTime, nullable=True) | ||
| issue_id = Column(Integer, nullable=True, index=True) | ||
| issue_id = Column(Integer, ForeignKey("issues.id"), nullable=True, index=True) | ||
|
||
|
|
||
| # Relationships | ||
| jurisdiction = relationship("Jurisdiction", back_populates="grievances") | ||
|
|
@@ -136,6 +136,9 @@ class Issue(Base): | |
| location = Column(String, nullable=True) | ||
| action_plan = Column(JSONEncodedDict, nullable=True) | ||
|
|
||
| # Relationships | ||
| grievances = relationship("Grievance", backref="issue") | ||
|
||
|
|
||
| class PushSubscription(Base): | ||
| __tablename__ = "push_subscriptions" | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical syntax error: malformed try/except structure.
The code has invalid indentation and a missing outer
tryblock. The innertry:at line 46 is incorrectly indented within the payload dictionary context, and theexceptat line 58 has no matchingtry. This will cause aSyntaxErrorand prevent the module from loading.Static analysis confirms: "Unexpected indentation" and "Expected a statement" errors.
🐛 Proposed fix for the malformed try/except structure
payload = { "inputs": image_base64, "parameters": { "candidate_labels": labels } } - try: - response = await client.post(API_URL, headers=headers, json=payload, timeout=20.0) - if response.status_code != 200: - logger.error(f"HF API Error: {response.status_code} - {response.text}") - raise ExternalAPIException("Hugging Face API", f"HTTP {response.status_code}: {response.text}") - return response.json() - except httpx.HTTPError as e: - logger.error(f"HF API HTTP Error: {e}") - raise ExternalAPIException("Hugging Face API", str(e)) from e - except Exception as e: - logger.error(f"HF API Request Exception: {e}") - raise ExternalAPIException("Hugging Face API", str(e)) from e - except Exception as e: - logger.error(f"Error preparing HF API request: {e}") - raise ExternalAPIException("Hugging Face API", str(e)) from e + try: + response = await client.post(API_URL, headers=headers, json=payload, timeout=20.0) + if response.status_code != 200: + logger.error(f"HF API Error: {response.status_code} - {response.text}") + raise ExternalAPIException("Hugging Face API", f"HTTP {response.status_code}: {response.text}") + return response.json() + except httpx.HTTPError as e: + logger.error(f"HF API HTTP Error: {e}") + raise ExternalAPIException("Hugging Face API", str(e)) from e + except Exception as e: + logger.error(f"HF API Request Exception: {e}") + raise ExternalAPIException("Hugging Face API", str(e)) from e📝 Committable suggestion
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 46-46: Unexpected indentation
(invalid-syntax)
[warning] 58-58: Expected a statement
(invalid-syntax)
[warning] 58-58: Expected a statement
(invalid-syntax)
[warning] 58-59: Expected an expression
(invalid-syntax)
[warning] 59-59: Unexpected indentation
(invalid-syntax)
🤖 Prompt for AI Agents