SuhasGholkar commited on
Commit
b9b004c
·
verified ·
1 Parent(s): ffab89e

Update src/utils.py

Browse files
Files changed (1) hide show
  1. src/utils.py +63 -36
src/utils.py CHANGED
@@ -1,44 +1,71 @@
1
  # src/utils.py
2
- import os
3
- import sqlite3
4
- import pathlib
5
- from datetime import datetime
6
- import streamlit as st
7
 
8
- APP_DIR = pathlib.Path(__file__).resolve().parent.parent
9
- DB_PATH = APP_DIR / "olist.sqlite"
 
 
 
 
 
 
 
10
 
11
- # Make local writable dirs for caches
12
- os.environ.setdefault("HOME", str(APP_DIR))
13
- os.environ.setdefault("XDG_CACHE_HOME", str(APP_DIR / ".cache"))
14
- os.environ.setdefault("MPLCONFIGDIR", str(APP_DIR / ".mplconfig"))
15
- os.makedirs(APP_DIR / ".cache", exist_ok=True)
16
- os.makedirs(APP_DIR / ".mplconfig", exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def ensure_db_present():
19
- """Ensure olist.sqlite is present at DB_PATH (copy from repo if needed)."""
20
  if DB_PATH.exists():
21
  return
22
- # repo copy
23
- repo_db = APP_DIR / "olist.sqlite"
24
- if repo_db.exists():
25
- repo_db.replace(DB_PATH)
26
- return
27
- # optional: download from HF Hub if configured
28
- try:
29
- from huggingface_hub import hf_hub_download
30
- repo_id = os.getenv("HF_DB_REPO")
31
- filename = os.getenv("HF_DB_FILE", "olist.sqlite")
32
- token = os.getenv("HF_TOKEN")
33
- if repo_id:
34
- local = hf_hub_download(repo_id=repo_id, filename=filename, token=token)
35
- pathlib.Path(local).replace(DB_PATH)
36
- except Exception:
37
- pass
38
 
39
- ensure_db_present()
 
 
 
 
 
 
 
 
40
 
41
- def get_connection() -> sqlite3.Connection:
42
- uri = f"file:{DB_PATH}?mode=rwc"
43
- conn = sqlite3.connect(uri, uri=True, check_same_thread=False)
44
- return conn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # src/utils.py
2
+ import os, sqlite3, shutil, logging, sys
3
+ from pathlib import Path
 
 
 
4
 
5
+ # ---- logging (goes to HF Runtime logs) ----
6
+ LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
7
+ logging.basicConfig(
8
+ stream=sys.stdout,
9
+ level=getattr(logging, LOG_LEVEL, logging.INFO),
10
+ format="%(asctime)s %(levelname)s [utils] %(message)s",
11
+ force=True,
12
+ )
13
+ ulog = logging.getLogger("utils")
14
 
15
+ # Repo root (/home/user/app)
16
+ APP_DIR = Path(__file__).resolve().parents[1]
17
+
18
+ # Single source of truth for DB location:
19
+ # - Default to Hugging Face persistent volume at /data
20
+ # - Can be overridden via env var DB_PATH if needed
21
+ DB_PATH = Path(os.environ.get("DB_PATH", "/data/olist.sqlite"))
22
+
23
+ def _ensure_db_file():
24
+ """
25
+ Ensure the DB file exists in the persistent volume.
26
+ If missing, seed from the repo copy (/app/olist.sqlite) if present,
27
+ otherwise create an empty DB (schemas will be created by init_auth_schema()).
28
+ """
29
+ try:
30
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)
31
+ except Exception as e:
32
+ ulog.exception("db: could not create parent dir for %s: %s", DB_PATH, e)
33
 
 
 
34
  if DB_PATH.exists():
35
  return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ seed = APP_DIR / "olist.sqlite" # committed file in your repo (if any)
38
+ if seed.exists():
39
+ try:
40
+ shutil.copy2(seed, DB_PATH)
41
+ ulog.info("db: seeded %s from %s", DB_PATH, seed)
42
+ except Exception as e:
43
+ ulog.exception("db: failed to seed from %s → %s: %s", seed, DB_PATH, e)
44
+ else:
45
+ ulog.warning("db: no seed DB found at %s; will create empty DB at %s", seed, DB_PATH)
46
 
47
+ def get_connection():
48
+ """
49
+ Open a connection to the persistent DB.
50
+ Logs path and PRAGMA database_list so you can verify which file is used.
51
+ """
52
+ _ensure_db_file()
53
+ try:
54
+ conn = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=30)
55
+ conn.execute("PRAGMA foreign_keys = ON;")
56
+ # Diagnostics
57
+ try:
58
+ size = DB_PATH.stat().st_size if DB_PATH.exists() else 0
59
+ except Exception:
60
+ size = -1
61
+ ulog.debug("db: open path=%s exists=%s size=%s bytes",
62
+ DB_PATH, DB_PATH.exists(), size)
63
+ try:
64
+ dblist = conn.execute("PRAGMA database_list").fetchall()
65
+ ulog.debug("db: PRAGMA database_list => %s", dblist)
66
+ except Exception as e:
67
+ ulog.debug("db: PRAGMA database_list failed: %s", e)
68
+ return conn
69
+ except Exception as e:
70
+ ulog.exception("db: connect failed for %s: %s", DB_PATH, e)
71
+ raise