yougandar commited on
Commit
07f0c5e
·
verified ·
1 Parent(s): c77ba39

Update db.py

Browse files
Files changed (1) hide show
  1. db.py +32 -59
db.py CHANGED
@@ -1,74 +1,47 @@
1
  import os
2
  import psycopg2
 
3
 
4
- DB_URL = os.getenv("DATABASE_URL") # Set this in Hugging Face Space Secrets
 
5
 
 
 
6
 
7
  def get_connection():
8
- """
9
- Returns a Postgres connection if DATABASE_URL is set,
10
- otherwise raises RuntimeError (caught in fallback functions).
11
- """
12
- if not DB_URL:
13
- raise RuntimeError("DATABASE_URL is not set. Using fallback (mock mode).")
14
- return psycopg2.connect(DB_URL)
15
-
16
 
17
  def get_table_status():
18
  """
19
- Example: Fetch current table occupancy status.
20
- Returns mock data if DB not available.
21
  """
22
- try:
23
- conn = get_connection()
24
- cur = conn.cursor()
25
- cur.execute("SELECT table_id, occupied FROM tables ORDER BY table_id;")
26
  rows = cur.fetchall()
27
- cur.close()
28
- conn.close()
29
- return [{"table_id": r[0], "occupied": r[1]} for r in rows]
30
-
31
- except Exception as e:
32
- print("⚠️ DB not available, using mock table status:", e)
33
- # fallback mock data
34
- return [
35
- {"table_id": 1, "occupied": True},
36
- {"table_id": 2, "occupied": False},
37
- {"table_id": 3, "occupied": True},
38
- ]
39
-
40
-
41
- def log_customer_visit(customer_name: str):
42
- """
43
- Log when a customer is detected/recognized.
44
- """
45
- try:
46
- conn = get_connection()
47
- cur = conn.cursor()
48
- cur.execute("INSERT INTO visits (customer_name) VALUES (%s);", (customer_name,))
49
  conn.commit()
50
- cur.close()
51
- conn.close()
52
- except Exception as e:
53
- print(f"⚠️ Could not log visit to DB ({e}). Customer:", customer_name)
54
-
55
 
56
  def get_alerts():
57
- """
58
- Fetch alerts from DB if available, otherwise return mock data.
59
- """
60
- try:
61
- conn = get_connection()
62
- cur = conn.cursor()
63
- cur.execute("SELECT id, message FROM alerts ORDER BY id DESC LIMIT 10;")
64
  rows = cur.fetchall()
65
- cur.close()
66
- conn.close()
67
- return [{"id": r[0], "message": r[1]} for r in rows]
68
-
69
- except Exception as e:
70
- print("⚠️ DB not available, using mock alerts:", e)
71
- return [
72
- {"id": 1, "message": "Mock Alert: No DB connection"},
73
- {"id": 2, "message": "System running in fallback mode"},
74
- ]
 
1
  import os
2
  import psycopg2
3
+ from psycopg2.extras import RealDictCursor
4
 
5
+ DB_URL = os.getenv("DB_URL") # e.g. postgres://user:pass@host:5432/dbname
6
+ ENABLE_DB = os.getenv("ENABLE_DB", "0") == "1"
7
 
8
+ def db_enabled() -> bool:
9
+ return ENABLE_DB and bool(DB_URL)
10
 
11
  def get_connection():
12
+ if not db_enabled():
13
+ raise RuntimeError("DB disabled or DB_URL not set")
14
+ return psycopg2.connect(DB_URL, connect_timeout=5)
 
 
 
 
 
15
 
16
  def get_table_status():
17
  """
18
+ Return a dict like {table_id: status}. If DB is disabled, return {}.
 
19
  """
20
+ if not db_enabled():
21
+ return {}
22
+ with get_connection() as conn, conn.cursor() as cur:
23
+ cur.execute("SELECT table_id, status FROM tables")
24
  rows = cur.fetchall()
25
+ return {row[0]: row[1] for row in rows}
26
+
27
+ def log_customer_visit(face_id: str, timestamp, table_id: int):
28
+ if not db_enabled():
29
+ return
30
+ with get_connection() as conn, conn.cursor() as cur:
31
+ cur.execute(
32
+ "INSERT INTO visits (face_id, timestamp, table_id) VALUES (%s, %s, %s)",
33
+ (face_id, timestamp, table_id),
34
+ )
 
 
 
 
 
 
 
 
 
 
 
 
35
  conn.commit()
 
 
 
 
 
36
 
37
  def get_alerts():
38
+ if not db_enabled():
39
+ return []
40
+ with get_connection() as conn, conn.cursor(cursor_factory=RealDictCursor) as cur:
41
+ cur.execute("SELECT type, trigger_time FROM alerts WHERE status='active'")
 
 
 
42
  rows = cur.fetchall()
43
+ # Convert datetimes to isoformat for JSON friendliness
44
+ for r in rows:
45
+ if "trigger_time" in r and r["trigger_time"] is not None:
46
+ r["trigger_time"] = r["trigger_time"].isoformat()
47
+ return rows