Sahm269 commited on
Commit
c7d722a
·
verified ·
1 Parent(s): 24ae56d

Delete server/db/db_sqlite.py

Browse files
Files changed (1) hide show
  1. server/db/db_sqlite.py +0 -158
server/db/db_sqlite.py DELETED
@@ -1,158 +0,0 @@
1
- import streamlit as st
2
- import sqlite3
3
- from mistralai import Mistral
4
- from datetime import datetime
5
- import logging
6
- import platform
7
- from dotenv import load_dotenv
8
- import os
9
-
10
- # Configuration du logging
11
- logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler()])
12
- logger = logging.getLogger(__name__)
13
-
14
- if platform.system() == "Windows":
15
- # Specify the path to your .env file
16
- dotenv_path = os.path.join(os.path.dirname(__file__), '..', '..', '.env')
17
- # Load the .env file
18
- load_dotenv(dotenv_path)
19
- else:
20
- load_dotenv()
21
-
22
-
23
-
24
-
25
- # Establish PostgreSQL connection
26
- # try:
27
- # db = psycopg2.connect(
28
- # host=os.environ.get("POSTGRES_HOST"),
29
- # user=os.environ.get("POSTGRES_USER"),
30
- # password=os.environ.get("POSTGRES_PASSWORD"),
31
- # dbname=os.environ.get("POSTGRES_DBNAME"),
32
- # port=os.environ.get("POSTGRES_PORT")
33
- # )
34
- # except psycopg2.OperationalError as err:
35
- # logger.error(f"Operational error: {err}")
36
- # except psycopg2.Error as err:
37
- # logger.error(f"Database connection error: {err}")
38
-
39
-
40
-
41
- # Configuration de la base de données SQLite
42
- DB_NAME = "chat_history.db"
43
- conn = sqlite3.connect(DB_NAME, check_same_thread=False)
44
- # Initialisation du client Mistral
45
- # api_key = "RXjfbTO7wkOU0RwrwP7XpFfcj1K5eq40"
46
- # api_key = os.environ.get("MISTRAL_API_KEY")
47
- # mistral_client = Mistral(api_key=api_key)
48
-
49
- def get_cursor():
50
- """
51
- Validate and obtain a cursor for database operations.
52
-
53
- Returns:
54
- cursor: A database cursor.
55
- """
56
- try:
57
- return conn.cursor()
58
- except sqlite3.Error as err:
59
- logger.error(f"Error obtaining cursor: {err}")
60
- return None
61
-
62
-
63
- def init_db():
64
- cursor = get_cursor()
65
- try:
66
- cursor.execute('''
67
- CREATE TABLE IF NOT EXISTS conversations (
68
- id INTEGER PRIMARY KEY AUTOINCREMENT,
69
- created_at TEXT NOT NULL,
70
- title TEXT NOT NULL
71
- )
72
- ''')
73
- cursor.execute('''
74
- CREATE TABLE IF NOT EXISTS messages (
75
- id INTEGER PRIMARY KEY AUTOINCREMENT,
76
- conversation_id INTEGER NOT NULL,
77
- role TEXT NOT NULL,
78
- content TEXT NOT NULL,
79
- timestamp TEXT NOT NULL,
80
- FOREIGN KEY (conversation_id) REFERENCES conversations (id)
81
- )
82
- ''')
83
- return
84
- except sqlite3.Error as err:
85
- logger.error(f"Error while connecting to database: {err}")
86
- return
87
- raise HTTPException(status_code=500, detail=str(err))
88
- finally:
89
- conn.commit()
90
- # conn.close()
91
-
92
-
93
- def save_message(conversation_id, role, content):
94
- cursor = get_cursor()
95
- try:
96
- timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
97
- cursor.execute("INSERT INTO messages (conversation_id, role, content, timestamp) VALUES (?, ?, ?, ?)",
98
- (conversation_id, role, content, timestamp))
99
- except sqlite3.Error as err:
100
- logger.error(f"Error while connecting to database: {err}")
101
- return
102
- raise HTTPException(status_code=500, detail=str(err))
103
- finally:
104
- conn.commit()
105
- # conn.close()
106
-
107
- def create_conversation(title):
108
- cursor = get_cursor()
109
- try:
110
- created_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
111
- cursor.execute("INSERT INTO conversations (created_at, title) VALUES (?, ?)", (created_at, title))
112
- conversation_id = cursor.lastrowid
113
- return conversation_id
114
- except sqlite3.Error as err:
115
- logger.error(f"Error while connecting to database: {err}")
116
- raise Exception(status_code=500, detail=str(err))
117
- finally:
118
- conn.commit()
119
- # conn.close()
120
-
121
-
122
- def load_messages(conversation_id):
123
- cursor = get_cursor()
124
- try:
125
- cursor.execute("SELECT role, content FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC", (conversation_id,))
126
- data = [{"role": row[0], "content": row[1]} for row in cursor.fetchall()]
127
- return data
128
- except sqlite3.Error as err:
129
- logger.error(f"Error while connecting to database: {err}")
130
- raise Exception(status_code=500, detail=str(err))
131
- finally:
132
- conn.commit()
133
- # conn.close()
134
-
135
- def load_conversations():
136
- cursor = get_cursor()
137
- try:
138
- cursor.execute("SELECT * FROM conversations ORDER BY created_at DESC")
139
- data = cursor.fetchall()
140
- return data
141
- except sqlite3.Error as err:
142
- logger.error(f"Error while connecting to database: {err}")
143
- raise Exception(status_code=500, detail=str(err))
144
- finally:
145
- conn.commit()
146
- # conn.close()
147
-
148
- def update_conversation(conversation_id):
149
- cursor = get_cursor()
150
- try:
151
- new_timer = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
152
- cursor.execute("UPDATE conversations SET created_at = ? WHERE id = ?",(new_timer, conversation_id))
153
- except sqlite3.Error as err:
154
- logger.error(f"Error while connecting to database: {err}")
155
- raise Exception(status_code=500, detail=str(err))
156
- finally:
157
- conn.commit()
158
- # conn.close()