Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,16 +2,16 @@ import sys
|
|
| 2 |
import os
|
| 3 |
import uvicorn
|
| 4 |
import re
|
| 5 |
-
from fastapi import FastAPI
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
-
from fastapi.responses import HTMLResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from typing import List, Optional
|
| 10 |
|
| 11 |
# π¨ FORCE PYTHON TO FIND THE 'src' FOLDER
|
| 12 |
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 13 |
|
| 14 |
-
# Import
|
| 15 |
from src.db_connector import Database
|
| 16 |
from src.rag_manager import RAGSystem
|
| 17 |
from src.sql_generator import SQLGenerator
|
|
@@ -32,20 +32,22 @@ class ChatRequest(BaseModel):
|
|
| 32 |
|
| 33 |
# --- HELPER: CLEAN AI OUTPUT ---
|
| 34 |
def clean_sql(sql_text: str) -> str:
|
| 35 |
-
|
| 36 |
-
if not sql_text:
|
| 37 |
-
return ""
|
| 38 |
-
# Remove markdown code blocks (```sql ... ```)
|
| 39 |
cleaned = re.sub(r"```sql|```", "", sql_text, flags=re.IGNORECASE).strip()
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
# --- INITIALIZATION SEQUENCE ---
|
| 45 |
print("--- π SYSTEM STARTUP SEQUENCE ---")
|
| 46 |
try:
|
| 47 |
print(" ...Connecting to Database")
|
| 48 |
-
|
|
|
|
| 49 |
print(" β
Database Connection: SUCCESS")
|
| 50 |
|
| 51 |
print(" ...Initializing RAG System")
|
|
@@ -57,85 +59,55 @@ try:
|
|
| 57 |
print(" β
AI Model: LOADED")
|
| 58 |
|
| 59 |
except Exception as e:
|
|
|
|
| 60 |
print(f" β CRITICAL STARTUP ERROR: {e}")
|
| 61 |
|
| 62 |
-
|
| 63 |
-
# --- 1. NEW ROUTE TO SERVE THE UI ---
|
| 64 |
@app.get("/", response_class=HTMLResponse)
|
| 65 |
async def serve_ui():
|
| 66 |
-
"""Serves the index.html file when user visits the root URL"""
|
| 67 |
try:
|
| 68 |
with open("index.html", "r", encoding="utf-8") as f:
|
| 69 |
return f.read()
|
| 70 |
except FileNotFoundError:
|
| 71 |
-
return "Error: index.html not found.
|
| 72 |
-
|
| 73 |
|
| 74 |
-
# --- 2. CHAT API ENDPOINT ---
|
| 75 |
@app.post("/chat")
|
| 76 |
def chat_endpoint(request: ChatRequest):
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
try:
|
| 80 |
-
# 1. Get Context
|
| 81 |
context = rag.get_relevant_schema(request.question)
|
| 82 |
-
|
| 83 |
-
# 2. Generate SQL
|
| 84 |
raw_sql, explanation, friendly_msg = generator.generate_sql(request.question, context, request.history)
|
| 85 |
|
| 86 |
-
#
|
| 87 |
-
if "Error:" in raw_sql or "Invalid Query" in raw_sql:
|
| 88 |
-
return {
|
| 89 |
-
"answer": [],
|
| 90 |
-
"sql": raw_sql,
|
| 91 |
-
"message": "I couldn't generate a safe query for that request. Try asking for specific data like 'Show me users' or 'List orders'.",
|
| 92 |
-
"follow_ups": ["Show top 10 rows from users", "Count total orders"]
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
cleaned_sql = clean_sql(raw_sql)
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# Safety check: Ensure it's a SELECT
|
| 99 |
if not cleaned_sql.upper().startswith("SELECT"):
|
| 100 |
-
return {
|
| 101 |
-
"answer": [],
|
| 102 |
-
"sql": cleaned_sql,
|
| 103 |
-
"message": "Security Alert: I can only perform READ (SELECT) operations.",
|
| 104 |
-
"follow_ups": []
|
| 105 |
-
}
|
| 106 |
|
| 107 |
-
#
|
| 108 |
try:
|
| 109 |
results = db.run_query(cleaned_sql)
|
| 110 |
except Exception as db_err:
|
| 111 |
-
|
| 112 |
-
return {
|
| 113 |
-
"answer": [f"Error: {str(db_err)}"],
|
| 114 |
-
"sql": cleaned_sql,
|
| 115 |
-
"message": "There was a syntax error in the generated SQL. I have displayed the error above.",
|
| 116 |
-
"follow_ups": []
|
| 117 |
-
}
|
| 118 |
-
|
| 119 |
-
# 5. Generate Follow-ups
|
| 120 |
-
follow_ups = generator.generate_followup_questions(request.question, cleaned_sql)
|
| 121 |
|
| 122 |
return {
|
| 123 |
"answer": results,
|
| 124 |
"sql": cleaned_sql,
|
| 125 |
-
"explanation": explanation,
|
| 126 |
"message": friendly_msg,
|
| 127 |
-
"follow_ups":
|
| 128 |
}
|
| 129 |
|
| 130 |
except Exception as e:
|
| 131 |
-
|
| 132 |
-
return {
|
| 133 |
-
"answer": [],
|
| 134 |
-
"sql": "-- System Error",
|
| 135 |
-
"message": f"Critical Error: {str(e)}",
|
| 136 |
-
"follow_ups": []
|
| 137 |
-
}
|
| 138 |
|
| 139 |
if __name__ == "__main__":
|
| 140 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
| 141 |
-
|
|
|
|
| 2 |
import os
|
| 3 |
import uvicorn
|
| 4 |
import re
|
| 5 |
+
from fastapi import FastAPI
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
from fastapi.responses import HTMLResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from typing import List, Optional
|
| 10 |
|
| 11 |
# π¨ FORCE PYTHON TO FIND THE 'src' FOLDER
|
| 12 |
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 13 |
|
| 14 |
+
# Import custom modules
|
| 15 |
from src.db_connector import Database
|
| 16 |
from src.rag_manager import RAGSystem
|
| 17 |
from src.sql_generator import SQLGenerator
|
|
|
|
| 32 |
|
| 33 |
# --- HELPER: CLEAN AI OUTPUT ---
|
| 34 |
def clean_sql(sql_text: str) -> str:
|
| 35 |
+
if not sql_text: return ""
|
|
|
|
|
|
|
|
|
|
| 36 |
cleaned = re.sub(r"```sql|```", "", sql_text, flags=re.IGNORECASE).strip()
|
| 37 |
+
return cleaned.rstrip(';')
|
| 38 |
+
|
| 39 |
+
# --- π SAFE INITIALIZATION ---
|
| 40 |
+
# Initialize as None so the app doesn't crash if DB fails
|
| 41 |
+
db = None
|
| 42 |
+
rag = None
|
| 43 |
+
generator = None
|
| 44 |
+
startup_error = None
|
| 45 |
|
|
|
|
| 46 |
print("--- π SYSTEM STARTUP SEQUENCE ---")
|
| 47 |
try:
|
| 48 |
print(" ...Connecting to Database")
|
| 49 |
+
# β οΈ IF THIS FAILS, THE APP WILL NOW CATCH IT GRACEFULLY
|
| 50 |
+
db = Database()
|
| 51 |
print(" β
Database Connection: SUCCESS")
|
| 52 |
|
| 53 |
print(" ...Initializing RAG System")
|
|
|
|
| 59 |
print(" β
AI Model: LOADED")
|
| 60 |
|
| 61 |
except Exception as e:
|
| 62 |
+
startup_error = str(e)
|
| 63 |
print(f" β CRITICAL STARTUP ERROR: {e}")
|
| 64 |
|
| 65 |
+
# --- ROUTES ---
|
|
|
|
| 66 |
@app.get("/", response_class=HTMLResponse)
|
| 67 |
async def serve_ui():
|
|
|
|
| 68 |
try:
|
| 69 |
with open("index.html", "r", encoding="utf-8") as f:
|
| 70 |
return f.read()
|
| 71 |
except FileNotFoundError:
|
| 72 |
+
return "Error: index.html not found."
|
|
|
|
| 73 |
|
|
|
|
| 74 |
@app.post("/chat")
|
| 75 |
def chat_endpoint(request: ChatRequest):
|
| 76 |
+
# π¨ CHECK FOR STARTUP ERRORS FIRST
|
| 77 |
+
if rag is None or db is None:
|
| 78 |
+
return {
|
| 79 |
+
"answer": [f"System Error: {startup_error}"],
|
| 80 |
+
"sql": "-- Database Connection Failed",
|
| 81 |
+
"message": f"I cannot connect to the database. Reason: {startup_error}. Please check the Logs tab.",
|
| 82 |
+
"follow_ups": []
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
try:
|
|
|
|
| 86 |
context = rag.get_relevant_schema(request.question)
|
|
|
|
|
|
|
| 87 |
raw_sql, explanation, friendly_msg = generator.generate_sql(request.question, context, request.history)
|
| 88 |
|
| 89 |
+
# Clean SQL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
cleaned_sql = clean_sql(raw_sql)
|
| 91 |
+
|
| 92 |
+
# Security Check
|
|
|
|
| 93 |
if not cleaned_sql.upper().startswith("SELECT"):
|
| 94 |
+
return {"answer": [], "sql": cleaned_sql, "message": "Security Alert: Read-Only Mode.", "follow_ups": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# Run Query
|
| 97 |
try:
|
| 98 |
results = db.run_query(cleaned_sql)
|
| 99 |
except Exception as db_err:
|
| 100 |
+
return {"answer": [f"SQL Error: {str(db_err)}"], "sql": cleaned_sql, "message": "Syntax Error in SQL.", "follow_ups": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
return {
|
| 103 |
"answer": results,
|
| 104 |
"sql": cleaned_sql,
|
|
|
|
| 105 |
"message": friendly_msg,
|
| 106 |
+
"follow_ups": []
|
| 107 |
}
|
| 108 |
|
| 109 |
except Exception as e:
|
| 110 |
+
return {"answer": [], "sql": "-- Error", "message": f"Processing Error: {str(e)}", "follow_ups": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
if __name__ == "__main__":
|
| 113 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|