saim1309 commited on
Commit
b66b8d3
·
verified ·
1 Parent(s): 75944f0

Delete database.py

Browse files
Files changed (1) hide show
  1. database.py +0 -144
database.py DELETED
@@ -1,144 +0,0 @@
1
- import sqlite3
2
- import json
3
- from contextlib import contextmanager
4
- from typing import List, Dict, Any, Tuple
5
- from config import DB_PATH
6
-
7
- @contextmanager
8
- def get_db_connection():
9
- """Context manager for database connections."""
10
- conn = sqlite3.connect(DB_PATH)
11
- conn.row_factory = sqlite3.Row
12
- try:
13
- yield conn
14
- finally:
15
- conn.close()
16
-
17
- def fetch_all_embeddings(table: str) -> List[Tuple[int, str, List[float]]]:
18
- """Fetch all embeddings from a table."""
19
- with get_db_connection() as conn:
20
- cur = conn.cursor()
21
- cur.execute(f"SELECT id, full_text, embedding FROM {table}")
22
- rows = cur.fetchall()
23
-
24
- parsed = []
25
- for row in rows:
26
- try:
27
- parsed.append((row['id'], row['full_text'], json.loads(row['embedding'])))
28
- except (json.JSONDecodeError, TypeError):
29
- continue
30
- return parsed
31
-
32
- def fetch_row_by_id(table: str, row_id: int) -> Dict[str, Any]:
33
- """Fetch a single row by ID."""
34
- with get_db_connection() as conn:
35
- cur = conn.cursor()
36
- cur.execute(f"SELECT * FROM {table} WHERE id = ?", (row_id,))
37
- row = cur.fetchone()
38
- return dict(row) if row else {}
39
-
40
- def fetch_all_faq_embeddings() -> List[Tuple[int, str, str, List[float]]]:
41
- """Fetch all FAQ embeddings."""
42
- with get_db_connection() as conn:
43
- cur = conn.cursor()
44
- cur.execute("SELECT id, question, answer, embedding FROM faq_entries")
45
- rows = cur.fetchall()
46
-
47
- parsed = []
48
- for row in rows:
49
- try:
50
- parsed.append((row['id'], row['question'], row['answer'], json.loads(row['embedding'])))
51
- except (json.JSONDecodeError, TypeError):
52
- continue
53
- return parsed
54
-
55
- def log_question(question: str, session_id: str = None, category: str = None, answer: str = None):
56
- """Log a user question to the database with full context."""
57
- with get_db_connection() as conn:
58
- cur = conn.cursor()
59
-
60
- # Check if table has the new columns, if not just log question (migration safety)
61
- # Or better, just try insert with all columns assuming schema is up to date or we updated it.
62
- # Given schema.sql suggests full schema, we'll try full insert.
63
-
64
- try:
65
- cur.execute("""
66
- INSERT INTO question_logs (session_id, question, category, answer)
67
- VALUES (?, ?, ?, ?)
68
- """, (session_id, question, category, answer))
69
- except sqlite3.OperationalError:
70
- # Fallback for older schema versions
71
- cur.execute("INSERT INTO question_logs (question) VALUES (?)", (question,))
72
-
73
- conn.commit()
74
-
75
- def get_session_state(session_id: str) -> Dict[str, Any]:
76
- """Get session state from DB"""
77
- with get_db_connection() as conn:
78
- cur = conn.cursor()
79
- cur.execute("SELECT * FROM user_sessions WHERE session_id = ?", (session_id,))
80
- row = cur.fetchone()
81
- if row:
82
- return dict(row)
83
- return {"preference": None, "msg_count": 0, "clarification_count": 0, "knowledge_context": "{}"}
84
-
85
- def update_session_state(session_id: str, preference: str = None, increment_count: bool = True, increment_clarification: bool = False, reset_clarification: bool = False, knowledge_update: Dict = None):
86
- """Update session state with Knowledge Dictionary support"""
87
- with get_db_connection() as conn:
88
- cur = conn.cursor()
89
-
90
- # Check if exists
91
- cur.execute("SELECT preference, msg_count, clarification_count, knowledge_context FROM user_sessions WHERE session_id = ?", (session_id,))
92
- row = cur.fetchone()
93
-
94
- current_knowledge = {}
95
- if row:
96
- curr_pref, curr_count, curr_clarification, curr_knowledge_json = row
97
- try:
98
- current_knowledge = json.loads(curr_knowledge_json)
99
- except:
100
- current_knowledge = {}
101
-
102
- new_pref = preference if preference else curr_pref
103
- new_count = curr_count + 1 if increment_count else curr_count
104
-
105
- # 10-Message Memory Rule: Reset if we hit the limit
106
- if new_count > 10:
107
- print(f"🔄 Session {session_id} reached 10 messages. Resetting memory context.")
108
- new_count = 1
109
- new_pref = None
110
- current_knowledge = {}
111
- new_clarification = 0
112
- else:
113
- new_clarification = curr_clarification
114
- if reset_clarification:
115
- new_clarification = 0
116
- elif increment_clarification:
117
- new_clarification = curr_clarification + 1
118
-
119
- # Merge knowledge updates
120
- if knowledge_update:
121
- current_knowledge.update(knowledge_update)
122
-
123
- new_knowledge_json = json.dumps(current_knowledge)
124
-
125
- cur.execute("""
126
- UPDATE user_sessions
127
- SET preference = ?, msg_count = ?, clarification_count = ?, knowledge_context = ?, last_updated = CURRENT_TIMESTAMP
128
- WHERE session_id = ?
129
- """, (new_pref, new_count, new_clarification, new_knowledge_json, session_id))
130
- else:
131
- new_pref = preference
132
- new_count = 1 if increment_count else 0
133
- new_clarification = 1 if increment_clarification else 0
134
-
135
- if knowledge_update:
136
- current_knowledge.update(knowledge_update)
137
- new_knowledge_json = json.dumps(current_knowledge)
138
-
139
- cur.execute("""
140
- INSERT INTO user_sessions (session_id, preference, msg_count, clarification_count, knowledge_context)
141
- VALUES (?, ?, ?, ?, ?)
142
- """, (session_id, new_pref, new_count, new_clarification, new_knowledge_json))
143
-
144
- conn.commit()