|
| 1 | +import os |
| 2 | +import sqlite3 |
| 3 | +import shutil |
| 4 | +import logging |
| 5 | +from fastapi import APIRouter, UploadFile, File, Header, HTTPException |
| 6 | +from model.database import set_engine_url |
| 7 | +from agent.semantic_layer import SEMANTIC_SCHEMA |
| 8 | +from agent.build_index import build_index |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | +router = APIRouter() |
| 12 | + |
| 13 | +@router.post("/api/upload") |
| 14 | +async def upload_database( |
| 15 | + file: UploadFile = File(...), |
| 16 | + x_openai_key: str | None = Header(None) |
| 17 | +): |
| 18 | + try: |
| 19 | + # Require API Key to build the Chroma index |
| 20 | + api_key = x_openai_key or os.getenv("OPENAI_API_KEY") |
| 21 | + if not api_key: |
| 22 | + raise HTTPException(status_code=400, detail="OpenAI API Key is required to index the database.") |
| 23 | + |
| 24 | + # Temporarily set the env var so build_index uses it |
| 25 | + os.environ["OPENAI_API_KEY"] = api_key |
| 26 | + |
| 27 | + upload_dir = os.path.join(os.getcwd(), "data") |
| 28 | + os.makedirs(upload_dir, exist_ok=True) |
| 29 | + file_path = os.path.join(upload_dir, "uploaded.db") |
| 30 | + |
| 31 | + with open(file_path, "wb") as buffer: |
| 32 | + shutil.copyfileobj(file.file, buffer) |
| 33 | + |
| 34 | + # Update database engine |
| 35 | + set_engine_url(f"sqlite:///{file_path}") |
| 36 | + |
| 37 | + # Connect and extract tables |
| 38 | + conn = sqlite3.connect(file_path) |
| 39 | + cursor = conn.cursor() |
| 40 | + cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") |
| 41 | + tables = cursor.fetchall() |
| 42 | + |
| 43 | + new_schema = [] |
| 44 | + for table in tables: |
| 45 | + table_name = table[0] |
| 46 | + cursor.execute(f"PRAGMA table_info({table_name});") |
| 47 | + columns = cursor.fetchall() |
| 48 | + |
| 49 | + new_schema.append({ |
| 50 | + "table_name": table_name, |
| 51 | + "description": f"Custom uploaded table {table_name}", |
| 52 | + "columns": [{"name": col[1], "description": f"Column {col[1]} of type {col[2]}"} for col in columns] |
| 53 | + }) |
| 54 | + |
| 55 | + conn.close() |
| 56 | + |
| 57 | + # Update global semantic schema |
| 58 | + SEMANTIC_SCHEMA.clear() |
| 59 | + SEMANTIC_SCHEMA.extend(new_schema) |
| 60 | + |
| 61 | + # Build ChromaDB index |
| 62 | + build_index() |
| 63 | + |
| 64 | + return {"success": True, "message": f"Successfully loaded and indexed {len(new_schema)} tables."} |
| 65 | + except Exception as e: |
| 66 | + logger.error(f"Error processing upload: {e}") |
| 67 | + raise HTTPException(status_code=500, detail=str(e)) |
0 commit comments