Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line23456789101112131415161714 unmodified lines32333435363738394041424344454647484950515 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411 unmodified lineimport osimport uvicornimport refrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse # <--- ADDED THISfrom pydantic import BaseModelfrom typing import List, Optional# π¨ FORCE PYTHON TO FIND THE 'src' FOLDERsys.path.append(os.path.dirname(os.path.abspath(__file__)))# Import your custom modulesfrom src.db_connector import Databasefrom src.rag_manager import RAGSystemfrom src.sql_generator import SQLGenerator14 unmodified lines# --- HELPER: CLEAN AI OUTPUT ---def clean_sql(sql_text: str) -> str:"""Removes markdown, 'sql' tags, and extra whitespace."""if not sql_text:return ""# Remove markdown code blocks (```sql ... ```)cleaned = re.sub(r"```sql|```", "", sql_text, flags=re.IGNORECASE).strip()# Remove trailing semicolons for consistencycleaned = cleaned.rstrip(';')return cleaned# --- INITIALIZATION SEQUENCE ---print("--- π SYSTEM STARTUP SEQUENCE ---")try:print(" ...Connecting to Database")db = Database()print(" β Database Connection: SUCCESS")print(" ...Initializing RAG System")5 unmodified linesprint(" β AI Model: LOADED")except Exception as e:print(f" β CRITICAL STARTUP ERROR: {e}")# --- 1. NEW ROUTE TO SERVE THE UI ---@app.get("/", response_class=HTMLResponse)async def serve_ui():"""Serves the index.html file when user visits the root URL"""try:with open("index.html", "r", encoding="utf-8") as f:return f.read()except FileNotFoundError:return "Error: index.html not found. Make sure it is in the root folder."# --- 2. CHAT API ENDPOINT ---@app.post("/chat")def chat_endpoint(request: ChatRequest):print(f"\nπ¨ NEW REQUEST: {request.question}")try:# 1. Get Contextcontext = rag.get_relevant_schema(request.question)# 2. Generate SQLraw_sql, explanation, friendly_msg = generator.generate_sql(request.question, context, request.history)# 3. Clean and Validate SQLif "Error:" in raw_sql or "Invalid Query" in raw_sql:return {"answer": [],"sql": raw_sql,"message": "I couldn't generate a safe query for that request. Try asking for specific data like 'Show me users' or 'List orders'.","follow_ups": ["Show top 10 rows from users", "Count total orders"]}cleaned_sql = clean_sql(raw_sql)print(f" π§Ή Cleaned SQL: {cleaned_sql}")# Safety check: Ensure it's a SELECTif not cleaned_sql.upper().startswith("SELECT"):return {"answer": [],"sql": cleaned_sql,"message": "Security Alert: I can only perform READ (SELECT) operations.","follow_ups": []}# 4. Run Querytry:results = db.run_query(cleaned_sql)except Exception as db_err:print(f" β οΈ DB Error: {db_err}")return {"answer": [f"Error: {str(db_err)}"],"sql": cleaned_sql,"message": "There was a syntax error in the generated SQL. I have displayed the error above.","follow_ups": []}# 5. Generate Follow-upsfollow_ups = generator.generate_followup_questions(request.question, cleaned_sql)return {"answer": results,"sql": cleaned_sql,"explanation": explanation,"message": friendly_msg,"follow_ups": follow_ups}except Exception as e:print(f"β General Processing Error: {e}")return {"answer": [],"sql": "-- System Error","message": f"Critical Error: {str(e)}","follow_ups": []}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8000)1 unmodified line23456789101112131415161714 unmodified lines323334353637383940414243444546474849505152535 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131 unmodified lineimport osimport uvicornimport refrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponsefrom pydantic import BaseModelfrom typing import List, Optional# π¨ FORCE PYTHON TO FIND THE 'src' FOLDERsys.path.append(os.path.dirname(os.path.abspath(__file__)))# Import custom modulesfrom src.db_connector import Databasefrom src.rag_manager import RAGSystemfrom src.sql_generator import SQLGenerator14 unmodified lines# --- HELPER: CLEAN AI OUTPUT ---def clean_sql(sql_text: str) -> str:if not sql_text: return ""cleaned = re.sub(r"```sql|```", "", sql_text, flags=re.IGNORECASE).strip()return cleaned.rstrip(';')# --- π SAFE INITIALIZATION ---# Initialize as None so the app doesn't crash if DB failsdb = Nonerag = Nonegenerator = Nonestartup_error = Noneprint("--- π SYSTEM STARTUP SEQUENCE ---")try:print(" ...Connecting to Database")# β οΈ IF THIS FAILS, THE APP WILL NOW CATCH IT GRACEFULLYdb = Database()print(" β Database Connection: SUCCESS")print(" ...Initializing RAG System")5 unmodified linesprint(" β AI Model: LOADED")except Exception as e:startup_error = str(e)print(f" β CRITICAL STARTUP ERROR: {e}")# --- ROUTES ---@app.get("/", response_class=HTMLResponse)async def serve_ui():try:with open("index.html", "r", encoding="utf-8") as f:return f.read()except FileNotFoundError:return "Error: index.html not found."@app.post("/chat")def chat_endpoint(request: ChatRequest):# π¨ CHECK FOR STARTUP ERRORS FIRSTif rag is None or db is None:return {"answer": [f"System Error: {startup_error}"],"sql": "-- Database Connection Failed","message": f"I cannot connect to the database. Reason: {startup_error}. Please check the Logs tab.","follow_ups": []}try:context = rag.get_relevant_schema(request.question)raw_sql, explanation, friendly_msg = generator.generate_sql(request.question, context, request.history)# Clean SQLcleaned_sql = clean_sql(raw_sql)# Security Checkif not cleaned_sql.upper().startswith("SELECT"):return {"answer": [], "sql": cleaned_sql, "message": "Security Alert: Read-Only Mode.", "follow_ups": []}# Run Querytry:results = db.run_query(cleaned_sql)except Exception as db_err:return {"answer": [f"SQL Error: {str(db_err)}"], "sql": cleaned_sql, "message": "Syntax Error in SQL.", "follow_ups": []}return {"answer": results,"sql": cleaned_sql,"message": friendly_msg,"follow_ups": []}except Exception as e:return {"answer": [], "sql": "-- Error", "message": f"Processing Error: {str(e)}", "follow_ups": []}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+35-63