Huzaifa1435's picture
Deploy AI SQL Agent Backend
345a446
Raw History Blame Contribute Delete
15.3 kB
"""
AI SQL Agent - Backend Flask API
Local: python app.py
HF: gunicorn app:app
"""
import os
import sqlite3
import shutil
import json
from datetime import datetime
from pathlib import Path
from werkzeug.utils import secure_filename
import pandas as pd
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from agent import ask_ai
from config import MODEL_NAME
import database as db_module
# ==================== APP SETUP ====================
app = Flask(__name__)
CORS(app, origins="*")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATABASE_FOLDER = os.path.join(BASE_DIR, "databases")
BACKUP_FOLDER = os.path.join(BASE_DIR, "backup")
LOG_FOLDER = os.path.join(BASE_DIR, "logs")
ALLOWED_EXTENSIONS = {"db", "sqlite", "sqlite3"}
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50 MB
for folder in [DATABASE_FOLDER, BACKUP_FOLDER, LOG_FOLDER]:
os.makedirs(folder, exist_ok=True)
app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE
# ==================== STATE ====================
query_count = 0
message_count = 0
# ==================== HELPERS ====================
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def get_db_tables(db_path):
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall()]
conn.close()
return tables
except Exception:
return []
def get_table_info(db_path, table_name):
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(f"SELECT COUNT(*) FROM [{table_name}]")
row_count = cursor.fetchone()[0]
cursor.execute(f"PRAGMA table_info([{table_name}])")
columns = [row[1] for row in cursor.fetchall()]
conn.close()
return {
"name": table_name,
"rows": row_count,
"columns": columns,
"column_count": len(columns),
}
except Exception:
return None
def get_table_data(db_path, table_name, limit=100):
try:
conn = sqlite3.connect(db_path)
df = pd.read_sql_query(f"SELECT * FROM [{table_name}] LIMIT {limit}", conn)
conn.close()
return df.to_dict("records")
except Exception:
return []
def log_action(action, details):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_file = os.path.join(LOG_FOLDER, "activity.log")
with open(log_file, "a") as f:
f.write(f"[{timestamp}] {action}: {details}\n")
def current_db():
"""Return active DB path or None."""
path = db_module.get_db_path()
return path if path and os.path.exists(path) else None
# ==================== ROUTES: STATUS ====================
@app.route("/api/health", methods=["GET"])
def health_check():
return jsonify({"status": "ok", "timestamp": datetime.now().isoformat()})
@app.route("/api/status", methods=["GET"])
def get_status():
cdb = current_db()
tables = get_db_tables(cdb) if cdb else []
return jsonify({
"model": MODEL_NAME,
"database": os.path.basename(cdb) if cdb else "Not Connected",
"tables": len(tables),
"queries": query_count,
"messages": message_count,
"timestamp": datetime.now().isoformat(),
"version": "1.0.0",
})
# ==================== ROUTES: DATABASE ====================
@app.route("/api/upload-database", methods=["POST"])
def upload_database():
try:
if "file" not in request.files:
return jsonify({"error": "No file provided"}), 400
file = request.files["file"]
if not file or file.filename == "":
return jsonify({"error": "No file selected"}), 400
if not allowed_file(file.filename):
return jsonify({"error": "Invalid file type. Only .db, .sqlite, .sqlite3 allowed"}), 400
filename = secure_filename(file.filename) or "database.db"
filepath = os.path.join(DATABASE_FOLDER, filename)
file.save(filepath)
# Validate it's a real SQLite file
try:
conn = sqlite3.connect(filepath)
conn.execute("SELECT 1")
conn.close()
except Exception:
os.remove(filepath)
return jsonify({"error": "Invalid SQLite database file"}), 400
db_module.set_db_path(filepath)
tables = get_db_tables(filepath)
log_action("DATABASE_UPLOAD", f"Uploaded {filename}")
return jsonify({
"success": True,
"message": f"Database uploaded: {filename}",
"database": filename,
"tables": tables,
"table_count": len(tables),
})
except Exception as e:
log_action("ERROR", f"Upload failed: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/api/databases", methods=["GET"])
def list_databases():
try:
files = os.listdir(DATABASE_FOLDER)
databases = []
cdb = current_db()
for f in files:
fp = os.path.join(DATABASE_FOLDER, f)
if os.path.isfile(fp):
size = os.path.getsize(fp)
mtime = datetime.fromtimestamp(os.path.getmtime(fp))
databases.append({
"name": f,
"size": f"{size/1024:.2f} KB",
"modified": mtime.strftime("%Y-%m-%d %H:%M:%S"),
})
return jsonify({
"databases": databases,
"current": os.path.basename(cdb) if cdb else None,
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/select-database/<filename>", methods=["POST"])
def select_database(filename):
try:
filepath = os.path.join(DATABASE_FOLDER, secure_filename(filename))
if not os.path.exists(filepath):
return jsonify({"error": "Database not found"}), 404
conn = sqlite3.connect(filepath)
conn.execute("SELECT 1")
conn.close()
db_module.set_db_path(filepath)
tables = get_db_tables(filepath)
log_action("DATABASE_SELECT", filename)
return jsonify({
"success": True,
"database": filename,
"tables": tables,
"table_count": len(tables),
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/delete-database/<filename>", methods=["DELETE"])
def delete_database(filename):
try:
filepath = os.path.join(DATABASE_FOLDER, secure_filename(filename))
if not os.path.exists(filepath):
return jsonify({"error": "Database not found"}), 404
cdb = current_db()
if cdb and os.path.abspath(cdb) == os.path.abspath(filepath):
db_module.set_db_path(None)
os.remove(filepath)
log_action("DATABASE_DELETE", filename)
return jsonify({"success": True, "message": f"Deleted {filename}"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/download-database", methods=["GET"])
def download_database():
try:
cdb = current_db()
if not cdb:
return jsonify({"error": "No database selected"}), 400
log_action("DATABASE_DOWNLOAD", os.path.basename(cdb))
return send_file(
cdb,
as_attachment=True,
download_name=os.path.basename(cdb),
mimetype="application/octet-stream",
)
except Exception as e:
return jsonify({"error": str(e)}), 500
# ==================== ROUTES: TABLES ====================
@app.route("/api/tables", methods=["GET"])
def get_tables():
cdb = current_db()
if not cdb:
return jsonify({"error": "No database selected"}), 400
try:
tables = get_db_tables(cdb)
table_info = [get_table_info(cdb, t) for t in tables]
table_info = [t for t in table_info if t]
return jsonify({"tables": table_info, "total": len(table_info)})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/table/<table_name>", methods=["GET"])
def get_table(table_name):
cdb = current_db()
if not cdb:
return jsonify({"error": "No database selected"}), 400
try:
info = get_table_info(cdb, table_name)
data = get_table_data(cdb, table_name)
return jsonify({"table": table_name, "info": info, "data": data, "row_count": len(data)})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ==================== ROUTES: QUERY ====================
@app.route("/api/query", methods=["POST"])
def process_query():
global query_count, message_count
try:
body = request.get_json()
question = (body.get("question") or "").strip()
if not question:
return jsonify({"error": "Question cannot be empty"}), 400
cdb = current_db()
if not cdb:
return jsonify({"error": "No database selected. Please upload or select a database first."}), 400
answer, sql, result_df = ask_ai(question)
query_count += 1
message_count += 1
result_data = None
if isinstance(result_df, pd.DataFrame) and not result_df.empty:
result_data = result_df.to_dict("records")
sql_upper = sql.upper().strip()
if sql_upper.startswith("SELECT"):
operation = "SELECT"
elif sql_upper.startswith("INSERT"):
operation = "INSERT"
elif sql_upper.startswith("UPDATE"):
operation = "UPDATE"
elif sql_upper.startswith("DELETE"):
operation = "DELETE"
else:
operation = "UNKNOWN"
log_action("QUERY", f"{operation} | Q: {question[:60]}")
return jsonify({
"success": True,
"answer": answer,
"sql": sql,
"data": result_data,
"operation": operation,
"row_count": len(result_data) if result_data else 0,
"database": os.path.basename(cdb),
"timestamp": datetime.now().isoformat(),
})
except Exception as e:
log_action("ERROR", f"Query failed: {e}")
return jsonify({"error": str(e)}), 500
# ==================== ROUTES: BACKUP ====================
@app.route("/api/backup", methods=["POST"])
def create_backup():
cdb = current_db()
if not cdb:
return jsonify({"error": "No database selected"}), 400
try:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
base = os.path.splitext(os.path.basename(cdb))[0]
backup_name = f"{base}_backup_{ts}.db"
backup_path = os.path.join(BACKUP_FOLDER, backup_name)
shutil.copy2(cdb, backup_path)
log_action("BACKUP_CREATED", backup_name)
return jsonify({"success": True, "message": f"Backup created: {backup_name}", "backup": backup_name})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/backups", methods=["GET"])
def list_backups():
try:
files = os.listdir(BACKUP_FOLDER)
backups = []
for f in files:
fp = os.path.join(BACKUP_FOLDER, f)
if os.path.isfile(fp):
size = os.path.getsize(fp)
mtime = datetime.fromtimestamp(os.path.getmtime(fp))
backups.append({
"name": f,
"size": f"{size/1024:.2f} KB",
"created": mtime.strftime("%Y-%m-%d %H:%M:%S"),
})
backups.sort(key=lambda x: x["created"], reverse=True)
return jsonify({"backups": backups, "total": len(backups)})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/restore/<backup_name>", methods=["POST"])
def restore_backup(backup_name):
try:
backup_path = os.path.join(BACKUP_FOLDER, secure_filename(backup_name))
if not os.path.exists(backup_path):
return jsonify({"error": "Backup not found"}), 404
restore_name = backup_name.replace("_backup", "").split("_")[0] + ".db"
restore_path = os.path.join(DATABASE_FOLDER, restore_name)
shutil.copy2(backup_path, restore_path)
db_module.set_db_path(restore_path)
tables = get_db_tables(restore_path)
log_action("BACKUP_RESTORED", backup_name)
return jsonify({
"success": True,
"message": "Backup restored successfully",
"database": restore_name,
"tables": tables,
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/backup/<backup_name>", methods=["DELETE"])
def delete_backup(backup_name):
try:
backup_path = os.path.join(BACKUP_FOLDER, secure_filename(backup_name))
if not os.path.exists(backup_path):
return jsonify({"error": "Backup not found"}), 404
os.remove(backup_path)
log_action("BACKUP_DELETED", backup_name)
return jsonify({"success": True, "message": "Backup deleted"})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ==================== ROUTES: MANAGEMENT ====================
@app.route("/api/clear-all", methods=["POST"])
def clear_all():
try:
for folder in [DATABASE_FOLDER]:
for f in os.listdir(folder):
fp = os.path.join(folder, f)
if os.path.isfile(fp):
os.remove(fp)
db_module.set_db_path(None)
log_action("CLEAR_ALL", "Cleared all databases")
return jsonify({"success": True, "message": "All databases cleared (backups preserved)"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/logs", methods=["GET"])
def get_logs():
try:
log_file = os.path.join(LOG_FOLDER, "activity.log")
if not os.path.exists(log_file):
return jsonify({"logs": [], "total": 0})
with open(log_file, "r") as f:
logs = f.readlines()
logs = list(reversed(logs[-100:]))
return jsonify({"logs": logs, "total": len(logs)})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ==================== ERROR HANDLERS ====================
@app.errorhandler(404)
def not_found(e):
return jsonify({"error": "Not found"}), 404
@app.errorhandler(413)
def too_large(e):
return jsonify({"error": "File too large (max 50 MB)"}), 413
@app.errorhandler(500)
def server_error(e):
return jsonify({"error": "Internal server error"}), 500
# ==================== MAIN ====================
if __name__ == "__main__":
# Auto-load default DB if it exists
default_db = os.path.join(BASE_DIR, "database", "company.db")
if os.path.exists(default_db):
db_module.set_db_path(default_db)
print(f"✅ Default DB loaded: {default_db}")
print("=" * 60)
print("🚀 AI SQL Agent – Backend API")
print("=" * 60)
print(f"Model : {MODEL_NAME}")
print(f"API URL : http://localhost:5000")
print("=" * 60)
app.run(debug=True, host="0.0.0.0", port=5000)