SuhasGholkar commited on
Commit
55f9cb2
·
verified ·
1 Parent(s): 504965e

Create utils.py

Browse files
Files changed (1) hide show
  1. src/utils.py +44 -0
src/utils.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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