Spaces:
Sleeping
Sleeping
Update app.py
Browse files13 unmodified lines1415161718197 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172282 unmodified lines355356357358359360120 unmodified lines48148248348448548613 unmodified linesfrom langchain.tools import toolfrom langgraph.checkpoint.memory import InMemorySaver# ------------------------------------------------------------# 1. Environment configuration7 unmodified linesOPENAI_API_KEY = os.getenv("OPENAI_API_KEY")MODEL_NAME = os.getenv("MODEL_NAME", "openai:gpt-5.4")DATABASE_PATH = Path(os.getenv("DATABASE_PATH", "data/Chinook_Db2.sql"))# ------------------------------------------------------------# 2. Database helpers# ------------------------------------------------------------def resolve_database_path() -> Path:"""Resolve the SQLite database path.Default:- data/Chinook_Sqlite.sqliteYou can override it in Hugging Face Spaces with:DATABASE_PATH=/path/to/your/database.sqlite"""if DATABASE_PATH.exists():return DATABASE_PATHcommon_paths = [Path("Chinook_Sqlite.sqlite"),Path("chinook.db"),Path("Chinook.db"),Path("data/chinook.db"),Path("data/Chinook.db"),]for path in common_paths:if path.exists():return pathraise FileNotFoundError("SQLite database file was not found. ""Upload your database file or set DATABASE_PATH in Hugging Face Variables.")DB_PATH = resolve_database_path()def get_database_schema(db_path: Path) -> str:282 unmodified lines# 7. Gradio chat function# ------------------------------------------------------------def chat_with_sql_agent(message, history, thread_id):"""Handles one user message from Gradio.120 unmodified lines**Model:** `{MODEL_NAME}`**Database:** `{DB_PATH}`""")13 unmodified lines14151617181920212223242526277 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259282 unmodified lines542543544545546547548549550551552553554555556557558559560561562563564565566120 unmodified lines68768868969069169269313 unmodified linesfrom langchain.tools import toolfrom langgraph.checkpoint.memory import InMemorySaver# Optional Hugging Face ZeroGPU support.# This is useful only if you select ZeroGPU hardware in Space settings.# For this OpenAI API app, CPU Basic is recommended.try:import spacesexcept Exception:spaces = None# ------------------------------------------------------------# 1. Environment configuration7 unmodified linesOPENAI_API_KEY = os.getenv("OPENAI_API_KEY")MODEL_NAME = os.getenv("MODEL_NAME", "openai:gpt-5.4")# Download the real Chinook SQLite DB directly from GitHub.# This avoids manually uploading the DB file to Hugging Face Spaces.CHINOOK_URL = os.getenv("CHINOOK_URL","https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite",)# Local runtime path inside the Space.# You can override this with DATABASE_PATH if needed.DB_PATH = Path(os.getenv("DATABASE_PATH", "Chinook.db"))# ------------------------------------------------------------# Optional ZeroGPU mode# ------------------------------------------------------------# Recommended for this app: CPU Basic or CPU Upgrade.## Why?# - The LLM is called through the OpenAI API.# - The model is not loaded locally on Hugging Face.# - SQLite and Gradio do not require GPU.## If you selected ZeroGPU hardware and see "no GPU function",# keep USE_ZEROGPU=true. The @spaces.GPU decorator tells HF# that this function is allowed to request ZeroGPU.## If you run on CPU hardware, this can stay true; HF says the# decorator is effect-free in non-ZeroGPU environments.USE_ZEROGPU = os.getenv("USE_ZEROGPU", "true").strip().lower() in {"1","true","yes","y",}# ------------------------------------------------------------# 2. Database download + validation helpers# ------------------------------------------------------------APP_DIR = Path(__file__).resolve().parentdef is_sqlite_database_file(path: Path) -> bool:"""A valid SQLite database starts with:SQLite format 3\x00"""if not path.exists() or not path.is_file():return Falsetry:with open(path, "rb") as file:header = file.read(16)return header == b"SQLite format 3\x00"except Exception:return Falsedef inspect_file_type(path: Path) -> str:"""Diagnose common file issues."""if not path.exists():return "missing"if path.is_dir():return "directory"try:with open(path, "rb") as file:sample = file.read(4096)if sample.startswith(b"SQLite format 3\x00"):return "sqlite"if sample.startswith(b"PK"):return "zip_file"lower_sample = sample.lower()if b"version https://git-lfs.github.com/spec" in lower_sample:return "git_lfs_pointer"if b"<html" in lower_sample or b"<!doctype html" in lower_sample:return "html_file"text_sample = sample.decode("utf-8", errors="ignore").lower()sql_markers = ["create table","insert into","begin transaction","pragma foreign_keys","drop table",]if any(marker in text_sample for marker in sql_markers):return "sql_script"return "unknown"except Exception:return "unreadable"def resolve_runtime_db_path(path: Path) -> Path:"""Resolve DB path inside Hugging Face Spaces.If DATABASE_PATH is relative, place it relative to the app directory.Example:DATABASE_PATH=Chinook.dbbecomes:/home/user/app/Chinook.db"""if path.is_absolute():return pathreturn APP_DIR / pathdef download_file(url: str, output_path: Path) -> None:"""Download file using Python standard library.requests is intentionally avoided to keep requirements simpler."""import urllib.requestoutput_path.parent.mkdir(parents=True, exist_ok=True)request = urllib.request.Request(url,headers={"User-Agent": "Mozilla/5.0 HuggingFaceSpace SQLite Downloader",},)with urllib.request.urlopen(request, timeout=60) as response:content = response.read()output_path.write_bytes(content)def download_chinook_database_if_needed() -> Path:"""Download the real Chinook SQLite database from GitHub if needed.This function fixes:- missing DB files- corrupted files- HTML files saved as DB- Git LFS pointer files- SQL scripts renamed as .db/.sqlite"""runtime_db_path = resolve_runtime_db_path(DB_PATH)if is_sqlite_database_file(runtime_db_path):print(f"Using existing valid SQLite database: {runtime_db_path}")return runtime_db_pathif runtime_db_path.exists():existing_type = inspect_file_type(runtime_db_path)print(f"Existing database path is not valid SQLite: {runtime_db_path}. "f"Detected type: {existing_type}. Re-downloading...")try:runtime_db_path.unlink()except Exception:passelse:print(f"Database not found at {runtime_db_path}. Downloading...")print(f"Downloading Chinook database from: {CHINOOK_URL}")download_file(CHINOOK_URL, runtime_db_path)if not is_sqlite_database_file(runtime_db_path):detected_type = inspect_file_type(runtime_db_path)raise sqlite3.DatabaseError(f"""Downloaded file is not a valid SQLite database.Download URL:{CHINOOK_URL}Saved path:{runtime_db_path}Detected file type:{detected_type}Possible fixes:1. Check that CHINOOK_URL points to a raw SQLite file.2. Use this default URL:https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite3. Do not use a normal GitHub webpage URL.4. Do not use a .sql dump URL unless you add SQL conversion logic.""")print(f"Successfully downloaded valid SQLite database: {runtime_db_path}")print(f"Database size: {runtime_db_path.stat().st_size:,} bytes")return runtime_db_pathDB_PATH = download_chinook_database_if_needed()def get_database_schema(db_path: Path) -> str:282 unmodified lines# 7. Gradio chat function# ------------------------------------------------------------def zerogpu_compatible(fn):"""Optional Hugging Face ZeroGPU wrapper.If ZeroGPU hardware is selected, Hugging Face expects at leastone function to be decorated with @spaces.GPU.For this app, GPU is not technically required because the LLM runsthrough the OpenAI API. CPU Basic is recommended. This wrapper existsonly to make the Space compatible with ZeroGPU if selected."""if USE_ZEROGPU and spaces is not None:return spaces.GPU(duration=120)(fn)return fn@zerogpu_compatibledef chat_with_sql_agent(message, history, thread_id):"""Handles one user message from Gradio.120 unmodified lines**Model:** `{MODEL_NAME}`**Database:** `{DB_PATH}`**Hardware note:** CPU Basic is recommended. ZeroGPU compatibility is enabled for Spaces that require it.""")
app.py+231-24