Spaces:
Sleeping
Sleeping
| """FastAPI Backend for OpenNL2SQL - Simplified for HuggingFace Spaces | |
| Author: Amal SP | |
| Created: December 2025 | |
| """ | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import Optional, List, Dict, Any | |
| import os | |
| import logging | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Initialize FastAPI app | |
| app = FastAPI( | |
| title="OpenNL2SQL API", | |
| description="AI-powered Natural Language to SQL Analytics System", | |
| version="1.0.0" | |
| ) | |
| # CORS configuration | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Request/Response Models | |
| class QueryRequest(BaseModel): | |
| question: str | |
| session_id: Optional[str] = None | |
| class QueryResponse(BaseModel): | |
| success: bool | |
| sql: Optional[str] = None | |
| results: Optional[List[Dict[str, Any]]] = None | |
| sql_explanation: Optional[str] = None | |
| results_explanation: Optional[str] = None | |
| error: Optional[str] = None | |
| session_id: str | |
| async def root(): | |
| """Health check endpoint""" | |
| return { | |
| "status": "healthy", | |
| "service": "OpenNL2SQL API", | |
| "version": "1.0.0", | |
| "message": "FastAPI backend is running on Hugging Face Spaces!" | |
| } | |
| async def health_check(): | |
| """Detailed health check""" | |
| return { | |
| "status": "healthy", | |
| "groq_api_configured": bool(os.getenv("GROQ_API_KEY")), | |
| "service": "OpenNL2SQL API" | |
| } | |
| async def process_query(request: QueryRequest): | |
| """Process natural language query""" | |
| # For now, return a placeholder response | |
| # This will be integrated with GROQ API and full backend logic | |
| session_id = request.session_id or "demo-session" | |
| return QueryResponse( | |
| success=True, | |
| sql="SELECT * FROM demo_table LIMIT 10;", | |
| results=[{"status": "Backend is running! Full implementation coming soon."}], | |
| sql_explanation="This is a demo response. Full NL2SQL functionality will be integrated.", | |
| results_explanation="The backend is successfully deployed on Hugging Face Spaces.", | |
| session_id=session_id | |
| ) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |